您的位置:首页 > 编程语言 > C语言/C++

C#动态调用C++的Dll

2009-08-28 14:18 344 查看
C#动态调用C++的Dll函数
1. 动态调用dll需要使用LoadLibrary, GetProcAddress, FreeLibrary 3个系统的API函数,所以在C#中用一个类静态调用kernal32.dl. 如下:
class DllTest
{
// 调用API库函数
[DllImport("Kernel32")]
public static extern int LoadLibrary(String funcname);

[DllImport("Kernel32")]
public static extern int GetProcAddress(int handle,String funcname);

[DllImport("Kernel32")]
public static extern int FreeLibrary(int handle);
}

2. 然后在同一个类中将通过非托管函数名转换为对应的委托,如下
///<param name="dllModule">通过LoadLibrary获得的DLL句柄</param>
///<param name="functionName">非托管函数名</param>
///<param name="t">对应的委托类型</param>
///<returns>委托实例,可强制转换为适当的委托类型</returns>
public static Delegate GetFunctionAddress(int dllModule, string functionName, Type t)
{
int address = GetProcAddress(dllModule, functionName);
if (address == 0)
return null;
else
return Marshal.GetDelegateForFunctionPointer(new IntPtr(address), t);
}
3. 在函数调用的Namespace中申明一个委托
TestFun是委托名,里面的参数是C++的Dll中被调用函数的参数;
delegate void TestFun(int i);

4. 调用第一步引用的静态函数Loadlibrary ,在C#中没有定义HMODULE这个类型,所以这个地方用int类型:
int module = DllTest.LoadLibrary("TESTCSharp.dll");
if(module==0)
{
MessageBox.Show("LoadLibrary failed");
}
else{
MessageBox.Show("LoadLibrary success");
}

5. 定义一个委托类型的变量, 调用第二步通过非托管函数名转换为对应的委托. 并将其返回类型强制转化成定义的委托类型,并赋值给新创建的委托实力,调用委托的实例化.
Type _t = typeof(TestFun);
TestFun _test = (TestFun)DllTest.GetFunctionAddress(module, "mySum", _t);
_test(3);

6. 最后需要释放创建的对象
DllTest.FreeLibrary(module);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: