C++/CLI如何将cli::array<char,1>^转换为LPCSTR*解决E0167编译错误
解决方案
方案1:直接使用原生字符数组(改动最小,优先推荐)
你当前声明的deviceList是托管堆上的cli::array<char>^类型,而原生APIListDevices要求传入原生字符指针,直接把托管数组替换为原生栈数组即可,无需修改其他业务逻辑:
bool FindUsbDevice(void) { // 替换原托管数组声明为原生数组即可 char deviceList[10] = {0}; UINT deviceNumber = 0; DWORD error; CString deviceName[1]; if (hUSB != INVALID_HANDLE_VALUE) CloseUSBdevice(); SwitchtoUsb(); WaitingLoop(8000); // 原生数组名自动退化为指针,匹配API参数要求 deviceNumber = ListDevices(deviceList); if (deviceNumber > 0) { deviceName[0] = deviceList[0]; hUSB = DeviceOpen(deviceName[0].GetBuffer(deviceName[0].GetLength()), &error); deviceName[0].ReleaseBuffer(-1); return hUSB != INVALID_HANDLE_VALUE; } return false; }
方案2:保留托管数组,钉住后获取原生指针传入
如果后续业务逻辑确实需要用到deviceList的托管特性,可以用pin_ptr钉住托管数组防止GC移动,再拿到原生指针传入API:
bool FindUsbDevice(void) { const array<char>^ deviceList = gcnew array<char>(10, 0); UINT deviceNumber = 0; DWORD error; CString deviceName[1]; if (hUSB != INVALID_HANDLE_VALUE) CloseUSBdevice(); SwitchtoUsb(); WaitingLoop(8000); // 钉住托管数组首元素,获取原生指针 pin_ptr<char> pDeviceList = &deviceList[0]; deviceNumber = ListDevices(pDeviceList); if (deviceNumber > 0) { deviceName[0] = deviceList[0]; hUSB = DeviceOpen(deviceName[0].GetBuffer(deviceName[0].GetLength()), &error); deviceName[0].ReleaseBuffer(-1); return hUSB != INVALID_HANDLE_VALUE; } return false; }
注意:如果你的项目是Unicode编码,
LPCTSTR会解析为const wchar_t*,此时需要把数组类型改为TCHAR/WCHAR,避免宽字符/窄字符不匹配的问题。
内容的提问来源于stack exchange,提问作者Gimmacus
相关产品推荐
相关产品推荐

