代码之家  ›  专栏  ›  技术社区  ›  Jim Fell

将chlocal转换为lptstr

  •  2
  • Jim Fell  · 技术社区  · 15 年前

    A应该如何 HLOCAL 数据类型转换为 LPTSTR 数据类型?我正在尝试从Microsoft Working获取代码片段,这是唯一的错误,我不确定如何解决:

    // 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);
    

    思想是受欢迎的。谢谢。

    2 回复  |  直到 15 年前
        1
  •  5
  •   Hans Passant    15 年前

    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进行编译。%如果你愿意的话。我猜这是你真正的问题,使用wprintf()。

        2
  •  1
  •   Vantomex    15 年前
      buffer = (LPTSTR)LocalAlloc(LPTR, buffersize * 2);