0

我试图用来HeapAlloc()分配一个由SetupDiGetDeviceRegistryProperty().

里面GetDeviceInformation()我有:

HANDLE hHeap = GetProcessHeap();

while (SetupDiEnumDeviceInfo(DeviceInfoSet, MemberIndex++, DeviceInfoData)) 
{
    DWORD DataT;
    LPTSTR buffer = NULL;
    DWORD buffersize = 0;
    // port of device
    DWORD portnum = 0;

    GetRegistryProperty(DeviceInfoSet, DeviceInfoData, SPDRP_FRIENDLYNAME, 
         &DataT, buffer, &buffersize, &buffersize);

    if (!buffer) 
    {
        cerr << "Null Ptr!" << endl;
        exit(1);
    }
    // Do stuff, uninstall device


    if (buffer) HeapFree(hHeap, NULL, buffer); 

    }
}

在里面GetRegistryProperty()我有:

void GetRegistryProperty(HDEVINFO DeviceInfoSet, PSP_DEVINFO_DATA DeviceInfoData, 
    DWORD Property, PDWORD DataT, LPTSTR buffer, PDWORD buffersize, PDWORD size)
{


    HANDLE hHeap = GetProcessHeap();

    while (!SetupDiGetDeviceRegistryProperty(
        DeviceInfoSet,
        DeviceInfoData,
        Property, //SPDRP_FRIENDLYNAME or SPDRP_CLASS
        DataT, //&DataT
        (PBYTE)buffer,
        *buffersize,
        size)) //&buffersize
    {
        if (GetLastError() == ERROR_INSUFFICIENT_BUFFER)
        {
            // Change the buffer size.
            if (buffer) HeapFree(hHeap, NULL, buffer); 

            // Double the size to avoid problems on 
            // W2k MBCS systems per KB 888609. 
            buffer = (LPTSTR)HeapAlloc(hHeap, HEAP_ZERO_MEMORY |
                HEAP_GENERATE_EXCEPTIONS, *buffersize * 2);
        }
        else
        {
            // error handling
            break;
        }
    }
}

HeapAlloc()按预期工作(缓冲区被属性填充)直到GetRegistryProperty()返回。此时,缓冲区始终为 NULL。这也是预期的吗?如何返回一个 char * 指向一个在创建它的函数生命周期之后存在的数组?我假设我不明白 HeapAlloc() 是如何工作的。

我将它放在单独的函数中的原因是我想GetRegistryProperty()用不同的 s 多次调用DWORD Property。在我将代码移动到单独的函数之前,它运行良好。

4

2 回答 2

2

buffer通过引用传递(注意LPTSTR &):

void GetRegistryProperty(HDEVINFO DeviceInfoSet, PSP_DEVINFO_DATA DeviceInfoData, 
    DWORD Property, PDWORD DataT, LPTSTR& buffer, PDWORD buffersize, PDWORD size)
于 2012-11-21T03:06:51.920 回答
1

您是buffer按值传递的,因此在 GetRegistryProperty 中,当您重新分配它时,您只需覆盖 GetRegistryProperty 中的指针副本。

将 GetRegistryProperty 的签名更改为:

void GetRegistryProperty(HDEVINFO DeviceInfoSet, PSP_DEVINFO_DATA DeviceInfoData, DWORD Property, PDWORD DataT, LPTSTR& buffer, PDWORD buffersize, PDWORD size)
于 2012-11-21T03:09:07.947 回答