Converting HLOCAL to LPTSTR
How is should a HLOCAL
data type be converted to a LPTSTR
data type? I'm trying to get a code snippet from Microsoft working, and this is the only error, of which I'm not sure how to resolve:
// Create a HDEVINFO with all present devices.
hDevInfo = SetupDiGetClassDevs(NULL,
0, // Enumerator
0,
DIGCF_PRESENT | DIGCF_ALLCLASSES );
if (hDevInfo == INVALID_HANDLE_VALUE)
{
// Insert error handling here.
return NULL;
}
// Enumerate through all devices in Set.
Device开发者_JAVA技巧InfoData.cbSize = sizeof(SP_DEVINFO_DATA);
for (i=0;SetupDiEnumDeviceInfo(hDevInfo, i, &DeviceInfoData);i++)
{
DWORD DataT;
LPTSTR buffer = NULL;
DWORD buffersize = 0;
//
// Call function with null to begin with,
// then use the returned buffer size (doubled)
// to Alloc the buffer. Keep calling until
// success or an unknown failure.
//
// Double the returned buffersize to correct
// for underlying legacy CM functions that
// return an incorrect buffersize value on
// DBCS/MBCS systems.
//
while (!SetupDiGetDeviceRegistryProperty(
hDevInfo,
&DeviceInfoData,
SPDRP_DEVICEDESC,
&DataT,
(PBYTE)buffer,
buffersize,
&buffersize))
{
if (GetLastError() == ERROR_INSUFFICIENT_BUFFER)
{
// Change the buffer size.
if (buffer) LocalFree(buffer);
// Double the size to avoid problems on
// W2k MBCS systems per KB 888609.
buffer = LocalAlloc(LPTR,buffersize * 2); // <- Error Occurs Here
}
else
{
// Insert error handling here.
break;
}
}
printf("Result:[%s]\n",buffer);
if (buffer) LocalFree(buffer);
}
if ( GetLastError()!=NO_ERROR && GetLastError()!=ERROR_NO_MORE_ITEMS )
{
// Insert error handling here.
return NULL;
}
// Cleanup
SetupDiDestroyDeviceInfoList(hDevInfo);
Thoughts are welcome. Thanks.
LocalLock() returns the pointer. But this is 18 year old silliness, just use
// Change the buffer size.
delete buffer;
// Double the size to avoid problems on
// W2k MBCS systems per KB 888609.
buffer = new TCHAR[buffersize * 2];
Ignoring the ~7 year old silliness of still using TCHAR for a moment. Your printf() statement needs work, depending on whether or not you are compiling with Unicode. %ls if you do. I'm guessing that's your real problem, use wprintf().
buffer = (LPTSTR)LocalAlloc(LPTR, buffersize * 2);
精彩评论