Accessing a C++ .lib library from c#
I have a c++ library file (.lib). How can I access the functions within it开发者_运维知识库 from C#? I have read that I could wrap the library file in a c++ dll and expose the functions that way. Is that the only way? I am not the owner of the code, so my options are limited.
Wrap the C++ lib with a C++/CLI assembly.
C++/CLI allows you to mix managed and unmanaged code, serving as a bridge between C# and native C++. It's actually very straightforward and relatively easy to do, although it can get tedious if you have a lot of classes/functions to wrap.
Here is one example.
You can not access a c++ library file (.lib) directly. The best way is to have an unmanaged wrapper around your unmanaged code. Reference DllImportAttribute
.
There's a good example of it's usage in the MSDN help document:
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);
}
}
Also note: You can have a managed c++ wrapper around your c++ library, but it's better to write your wrapper in unmanaged c++ code.
精彩评论