我有一个 c++ 库文件(.lib),如何从 C# 中访问其中的函数?我已经了解到可以将库文件封装在 c++ dll 中以此暴露其中的函数。这是唯一的方法吗?由于不是代码的所有者,我的选项有限。
用C++/CLI程序集封装C++库。
C++/CLI允许您混合使用托管和非托管代码,作为C#和本机C++之间的桥梁。实际上,这是非常简单且相对容易的操作,但如果您需要封装很多类/函数,它可能会变得繁琐。
这里有一个示例。
你不能直接访问C++库文件(.lib)。最好的方法是在非托管代码周围有一个非托管包装器。参考DllImportAttribute
。
MSDN帮助文档中有一个很好的使用示例:
using System;
using System.Runtime.InteropServices;
class Example
{
// Use DllImport to import the Win32 MessageBox function.
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
public static extern int MessageBox(IntPtr hWnd, String text, String caption, uint type);
static void Main()
{
// Call the MessageBox function using platform invoke.
MessageBox(new IntPtr(0), "Hello World!", "Hello Dialog", 0);
}
}