【坑】Unity 中使用 C++DLL注意事项

3 篇文章 1 订阅
3 篇文章 0 订阅

Unity 中使用C# 与 C++DLL交互遇到的一些问题总结!!!如果对你有所帮助,请留下你的点赞

1.如何生成DPLCPP_USB_Notification.dll

这个就不说了,比较容易

2. C# 中引入c++ dll 方法

这个简单,直接上代码

//C++
	extern "C" __declspec(dllexport) int createListenerThread()
	{
		//TODO
		return 0;
	}

C#这边

	[DllImport("DPLCPP_USB_Notification.dll", CallingConvention = CallingConvention.Cdecl)]
	public static extern int createListenerThread();

3.C# 注入委托回调到c++ dll ,

C#

	// 委托定义,与C++回调函数的签名相匹配
	public delegate void CallbackDelegate(IntPtr intPtr, int d);

注意c# GC会导致回调函数内存被强制回收,所以GC问题需要处理一下,最后回收

        /// <summary>
        /// The register notification.
        /// </summary>
        public void RegisterNotification()
        {
            var callbackFunc = new CallbackDelegate(DeviceChangeNotify);
            s_GcHandle = GCHandle.Alloc(callbackFunc);

            registerCallback(callbackFunc);
        }
        
       /// <summary>
        /// The unregister notification.
        /// </summary>
        public void UnregisterNotification()
        {
            if (s_GcHandle.IsAllocated)
            {
                s_GcHandle.Free();
            }
        }

C++执行回调

void UpdateDevice(PDEV_BROADCAST_DEVICEINTERFACE pDevInf, WPARAM wParam)
{
	CString szDevId = pDevInf->dbcc_name;
	const char* s = CStringA(szDevId);
	if (callbackFunction != nullptr) {
		callbackFunction(pDevInf, wParam);
	}
}

4.传参问题

类型对照:
BSTR --------- StringBuilder
LPCTSTR --------- StringBuilder
LPCWSTR --------- IntPtr
handle---------IntPtr
hwnd-----------IntPtr
char *----------IntPtr
int * -----------ref int
int &-----------ref int
void *----------IntPtr
unsigned char *-----ref byte
Struct需要在C#里重新定义一个Struct

C#端 解析处理

在这里插入图片描述
对照解析即可

5. Unity IL2CPP 打包兼容性问题

不支持System.Window.Forms
不支持System.Window.Forms
不支持System.Window.Forms
重要的事情说3遍,如果遇到这种情况,只能用C++ dll 处理,然后引入过来使用

简单记录,若有疑问,欢迎留言交流

  • 4
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值