C#可以使用C++的Dll库吗?函数如何调用?

2025-05-07 03:47:29
推荐回答(1个)
回答(1):

显然是可以的.拿一个最简单的例子调用MessageBox这个API函数:

public delegate int DelegateMessageBox(IntPtr hwnd,string lpString,string lpCaption,int type);

IntPtr hModule = Kernel32.LoadLibrary("User32.dll");
if (hModule != IntPtr.Zero) {
IntPtr hProc = Kernel32.GetProcAddress(hModule, "MessageBoxA");
if (hProc != IntPtr.Zero) {
DelegateMessageBox messagebox = (DelegateMessageBox)Marshal.GetDelegateForFunctionPointer(hProc, typeof(DelegateMessageBox));
messagebox(IntPtr.Zero, "aaaa", "caption", 0);

//IntPtr MyMethodPointer = MyMessageBox.Method.MethodHandle.GetFunctionPointer();
}
Kernel32.FreeLibrary(hModule);
}

其中用到了其他几个API函数,我封装到了Kernel32这个类里.你自己查下就可以了.这个是掉的WINDOWS的DLL.
调自己的DLL就修改下LoadLibrary和GetProcAddress为你自己的就可以了.

指针可以传引用,函数指针可以传delegate,句柄在C#中传IntPtr类型就可以了