C#调用C++ DLL

这个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);

    }

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值