c++mallocnvapi

NvAPI_GPU_GetAllDisplayIds function not working as expected


I'm using NVAPI in C++ to modify NVIDIA display settings in my program.

I cannot successfully use the NvAPI_GPU_GetAllDisplayIds function. The status returned from calling it is NVAPI_INCOMPATIBLE_STRUCT_VERSION.

Here is my code:

int main() {
    NvAPI_Status status;

    NvPhysicalGpuHandle nvGPUHandle[64];
    NvU32 gpuCount;
    status = NvAPI_EnumPhysicalGPUs(nvGPUHandle, &gpuCount);
    if (NVAPI_OK != status) {
        cerr << "Failed to run function: NvAPI_EnumPhysicalGPUs\nStatus: " << status << endl;
        return 1;
    }
    if (gpuCount <= 0) {
        cerr << "No GPU's found" << endl;
        return 1;
    }

    for (unsigned i = 0; i < gpuCount; ++i) {
        const NvPhysicalGpuHandle& hPhysicalGpu = nvGPUHandle[i];

        NvU32 displayIdCount = 0;
        status = NvAPI_GPU_GetAllDisplayIds(hPhysicalGpu, nullptr, &displayIdCount);
        if (NVAPI_OK != status) {
            cerr << "Failed to run function: NvAPI_GPU_GetAllDisplayIds\nStatus: " << status << endl;
            return 1;
        }
        if (displayIdCount <= 0) {
            cerr << "No display's found" << endl;
            return 1;
        }

        NV_GPU_DISPLAYIDS* displayIds = static_cast<NV_GPU_DISPLAYIDS*>(malloc(sizeof(NV_GPU_DISPLAYIDS) * displayIdCount));
        status = NvAPI_GPU_GetAllDisplayIds(hPhysicalGpu, displayIds, &displayIdCount);
        if (NVAPI_OK != status) {
            // status is NVAPI_INCOMPATIBLE_STRUCT_VERSION (-9)
            cerr << "Failed to run function: NvAPI_GPU_GetAllDisplayIds\nStatus: " << status << endl;
            return 1;
        }
    }

    return 0;
}

Am I using malloc incorrectly or something? Thank you!


Solution

  • This is not documented directly in the NVAPI documentation page for that function, but you need to set the version on your malloc'ed displayIds structure before passing it in to NvAPI_GPU_GetAllDisplayIds. Add this line before the call:

    displayIds->version = NV_GPU_DISPLAYIDS_VER;
    

    This seems to be pretty standard throughout the NVAPI with other function calls as well.