这个demo包括简单函数,回调函数,指针类型的C#调用。void*和byte的互调。
个人不是很建议直接使用C#调用C++的自定义类型对象,建议用C#指针调用C++的自定义对象指针。
直接上代码:
//C++ DLL
struct A
{
int a;
};
typedef int(*logCallback)(char* msg);
typedef int(*write_packetFunc)(void *opaque, void *buf, int buf_size);
void test();
int test1();
A* test2();
void setLogCB(logCallback lg);
void setWritepacketCB(write_packetFunc func)
</pre><pre name="code" class="cpp">//C#
namespace Demo
{
class Test
{
private const string DLL_NAME = "test.dll";
[DllImport(DLL_NAME, EntryPoint = "test", CallingConvention = CallingConvention.Cdecl)]
public static extern void test();
[DllImport(DLL_NAME, EntryPoint = "test1", CallingConvention = CallingConvention.Cdecl)]
public static extern int test1();
[DllImport(DLL_NAME, EntryPoint = "test2", CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr test2();
[System.Runtime.InteropServices.UnmanagedFunctionPointer(System.Runtime.InteropServices.CallingConvention.Cdecl)]
public delegate void LOGcallback([MarshalAs(UnmanagedType.LPStr)]string msg);
[DllImport(DLL_NAME, EntryPoint = "setLogCB", CallingConvention = CallingConvention.Cdecl, SetLastError = true, CharSet = CharSet.Unicode)]
public static extern void setLogCB([MarshalAs(UnmanagedType.FunctionPtr)] LOGcallback callback);
[DllImport(DLL_NAME, EntryPoint = "setWritepacketCB", CallingConvention = CallingConvention.Cdecl, SetLastError = true, CharSet = CharSet.Unicode)]
public static extern void setWritepacketCB([MarshalAs(UnmanagedType.FunctionPtr)] CDSetWritePacket callback);
[System.Runtime.InteropServices.UnmanagedFunctionPointer(System.Runtime.InteropServices.CallingConvention.Cdecl)]
public delegate int CDSetWritePacket(IntPtr ptr, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)]byte[] buf, int size);
}
}