在 C++(www.cppentry.com) 中我们能够通过 LoadLibrary, GetProcAddress 来动态C#调用dll导出函数。在 C# 中也能够用这样的方式吗?
在 DotNet 2.0 里面这样是可以的, 这完全得益于 2.0新增的一个函数Marshal.GetDelegateForFunctionPointer 方法此方法在 .NET Framework 2.0 版中是新增的。将非托管函数指针转换为委托。
C#调用dll导出函数实例代码如下:
- publicdelegateintMsgBox(inthwnd,stringmsg,stringcpp,intok);
- [DllImport("Kernel32")]
- publicstaticexternintGetProcAddress(inthandle,Stringfuncname);
- [DllImport("Kernel32")]
- publicstaticexternintLoadLibrary(Stringfuncname);
- [DllImport("Kernel32")]
- publicstaticexternintFreeLibrary(inthandle);
- privatestaticDelegateGetAddress(intdllModule,stringfunctionname,Typet)
- {
- intaddr=GetProcAddress(dllModule,functionname);