从 LPTSTR 到 tstring 的转换会导致运行时错误
问题描述:
我正在尝试将 LPTSTR 变量转换为 tstring(即,unicode 应用程序中的 wstring 和 ANSI 中的字符串).
I am attempting to convert a LPTSTR variable to tstring(ie, wstring in a unicode application and string in ANSI).
我该如何进行这种转换?
我的代码尝试执行转换,但导致错误:调试断言失败!表达式:无效的空指针":
My code attempts to perform the conversion but it causes the error: "Debug Assertion Failed! Expression: invalid null pointer":
#ifdef UNICODE
#define tstring std::wstring
#else
#define tstring std::string
#endif
tstring TVManager::getDevicePropertyTEST(HDEVINFO hDevInfo, SP_DEVINFO_DATA deviceInfoData, DWORD flag)
{
DWORD dataT = 0;
DWORD buffersize = 0;
LPTSTR buffer = NULL;
while (!SetupDiGetDeviceRegistryProperty(hDevInfo, &deviceInfoData, flag, &dataT,
(PBYTE)buffer, buffersize, &buffersize))
{
if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
// Change the buffer size.
if (buffer)
LocalFree(buffer);
buffer = (LPTSTR)LocalAlloc(LPTR, buffersize);
}
else {
// Insert error handling here.
debug_print_ex("Else happened:", buffer);
break;
}
}
tstring propertyValue = tstring(buffer); // ERROR OCCURS HERE
if (buffer)
LocalFree(buffer);
return propertyValue;
}
答
您正在向 std::basic_string<>
的构造函数传递一个空指针 – 不好.假设您只想要一个空字符串,如果 buffer
为 null,则执行以下操作:
You're passing a null pointer to std::basic_string<>
's constructor – no good. Assuming you just want an empty string if buffer
is null, then do the following:
tstring propertyValue;
if (buffer)
propertyValue = buffer;