2010-10-26 26 views
2

如何將HLOCAL數據類型轉換爲LPTSTR數據類型?我想從微軟工作一段代碼,這是唯一的錯誤,其中我不知道如何解決:將HLOCAL轉換爲LPTSTR

// 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. 

DeviceInfoData.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); 

思想是值得歡迎的。謝謝。

+0

LocalAlloc()返回指向緩衝區的指針ala malloc();只是將它投射到LPTSTR。 – Luke 2010-10-26 20:57:23

回答

5

LocalLock()返回指針。但這是18歲的愚蠢,只是使用

 // Change the buffer size. 
     delete buffer; 
     // Double the size to avoid problems on 
     // W2k MBCS systems per KB 888609. 
     buffer = new TCHAR[buffersize * 2]; 

忽略〜7歲仍然使用TCHAR的愚蠢片刻。您的printf()語句需要工作,具體取決於您是否使用Unicode編譯。 %ls如果你這樣做。我猜這是你真正的問題,使用wprintf()。

1
buffer = (LPTSTR)LocalAlloc(LPTR, buffersize * 2); 
+0

這對我有用。謝謝 – amadib 2014-05-02 19:18:17