简体   繁体   中英

Why won't my EnumWindowProc compile in C?

I am trying to write a function that returns a HWND from a process ID but there is one small problem. I am getting the error "expected an identifier". It will only compile if I remove the & in window_data &data but then the function doesn't work.. Why is the & needed in the first place? The code compiles in C++ but not in C.

typedef struct
{
    DWORD dwProcessID;
    HWND hWnd;
} window_data;

BOOL CALLBACK EnumWindowsProc(HWND hwnd, LPARAM lParam)
{
    window_data &data = *(window_data*)lParam;
    DWORD dwProcessID = 0;

    GetWindowThreadProcessId(hwnd, &dwProcessID);
    if (dwProcessID != data.dwProcessID)
        return TRUE;

    data.hWnd = hwnd;
    return FALSE;
}

The C language does not support the reference declaration on variables, only C++ does, thus window_data &data is invalid.

If you want to do this in standard C, you can change to a pointer casted version instead:

BOOL CALLBACK EnumWindowsProc(HWND hwnd, LPARAM lParam)
{
    window_data *data = (window_data*)lParam;
    DWORD dwProcessID = 0;

    GetWindowThreadProcessId(hwnd, &dwProcessID);
    if (dwProcessID != data->dwProcessID)
        return TRUE;

    data->hWnd = hwnd;
    return FALSE;
}
window_data &data = *(window_data*)lParam;

In C there are no references like in C++. Thus, you can´t use window_data &data within C code. This is the reason why the program get compiled with a C++ compiler but not with a C compiler.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM