准备:

首先打开vc++ 6.0新建工程,选择Win32 Dynamic Link-Library,命名为stdLibrary

新建library.cpp文件,内容如下

#include <stdio.h>
#include <windows.h>

BOOL APIENTRY DllMain( HMODULE hModule,
                       DWORD  ul_reason_for_call,
                       LPVOID lpReserved)
{
    return TRUE;
}


 HRESULT __stdcall  TestAdd(int i, int j)
{
 return i + j;
}

接着新建Text File命名为export.def,内容如下

LIBRARY "stdLibrary"

EXPORTS
TestAdd @1

编译项目得到stdLibrary.dll

 

1 vb调用stdLibrary.dll

新建标准EXE工程,拖拽界面,如图

右键查看代码,编写如下代码

Private Declare Function TestAdd Lib "stdLibrary.dll" (ByVal InX As Long, ByVal InY As Long) As Long

Private Sub cmdCaclute_Click()
Dim x As Long
Dim y As Long
Dim result As Long

x = txtX.Text

y = txtY.Text

result = TestAdd(x, y)

txtResult.Text = result

End Sub

然后使用vb生成exe,把stdLibrary.dll拖拽到项目所在编译目录,运行即可,调用成功。

注意:vb调用第三方dll,调试过程 Lib “stdLibrary.dll”如果不是绝对路径会报错,不懂是不是vb的bug,只要生成exe后运行就不报错了

 

2 c#调用stdLibrary.dll

编写如下代码,并且把stdLibrary.dll拖拽到Debug/Release目录

using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;

namespace csharpcallcLibrary
{
    class Program
    {
        [DllImport("stdLibrary.dll", CallingConvention = CallingConvention.StdCall)]
        public static extern int TestAdd(int x, int y); 

        static void Main(string[] args)
        {
            int x = 1, y = 2,result=0;
            result=TestAdd(x, y);
            Console.WriteLine("{0} + {1} = {2}",x,y,result);
            Console.Read();
        }
    }
}

运行编译生成的exe,至此调用成功

posted on 2015-04-27 07:12  你不知道的浪漫  阅读(1561)  评论(0编辑  收藏  举报