C# 调用WCHBLEDLL库,WCH_Lib.WCHBLEGetAllServicesUUID函数很不稳定

按照接口文档,整体流程都跑通了,就是获取UUID列表的那几个函数不稳定;经过调试,UUID数组指向的内存地址明明有数据,但是读到的数组长度参数好几次都是0,需要去多次连续调用才有可能有值,非常令人抓狂!

        /// 
        /// 获取设备所有服务
        /// 
        /// 设备句柄
        /// 设备服务存放数组
        /// 服务个数
        /// 
        [DllImport(@".\Lib\WCHBLEDLL.dll")]
        public extern static byte WCHBLEGetAllServicesUUID(IntPtr pDev, IntPtr pUUIDArry, IntPtr pUUIDArryLen);


截取了关键部分,有按照文档的顺序调用接口

  //4. 获取设备服务标识ID
            ushort tryGetCount = 10, k = 0, deviceUUIDsLength = 0;
            while (k++ <= tryGetCount)
            {
                // 加点延时
                //Thread.Sleep(3000);
                Console.WriteLine($"*******************第{k}次获取服务UUID*******************");
                IntPtr pDeviceServiceUUIDsBuff = Marshal.AllocHGlobal(Marshal.SizeOf() * 100);
                IntPtr pDeviceServiceUUIDsLengthBuff = Marshal.AllocHGlobal(Marshal.SizeOf());
                var getAllServicesUUIDResult = WCH_Lib.WCHBLEGetAllServicesUUID(deviceConnectHandle, pDeviceServiceUUIDsBuff, pDeviceServiceUUIDsLengthBuff);
                Console.WriteLine($"查询设备服务UUID,res = {getAllServicesUUIDResult}");

                unsafe
                {
                    deviceUUIDsLength = *(ushort*)pDeviceServiceUUIDsLengthBuff;
                    Console.WriteLine($"服务UUID数量 = {deviceUUIDsLength}");
                    for (ushort i = 0; i < deviceUUIDsLength; i++)
                    {
                        ushort uuid = *(ushort*)(pDeviceServiceUUIDsBuff + i * Marshal.SizeOf());
                        Console.WriteLine($"{uuid.ToString("X4")}");
                    }
                }
                Marshal.FreeHGlobal(pDeviceServiceUUIDsLengthBuff);
                Marshal.FreeHGlobal(pDeviceServiceUUIDsBuff);
                Console.WriteLine("**************************************************************");
                if(deviceUUIDsLength > 0)
                {
                    break;
                }
            }


留个邮箱,我们相关工程师与你联系。


个人信息保护,已隐藏



已发送至邮箱,请查收。


已发送至邮箱,请查收。


只有登录才能回复,可以选择微信账号登录