Search code examples
c++visual-studiovisual-studio-2008mfcreinterpret-cast

Why does reinterpret_cast<int>(lParam); generate C2440 error?


I have a typical Windows Message handler for C++/MFC/32-bit with signature LRESULT CMyFrame::OnMyMessage(WPARAM wParam, LPARAM lParam)

I have written these two lines, preferring the first over the 2nd :

int iError = reinterpret_cast<int>(lParam);
int iWorks = (int)lParam;

I get a C2440 error on the first: error C2440: 'reinterpret_cast' : cannot convert from 'LPARAM' to 'int'

but the 2nd one compiles fine

This is C++, not C, hence I prefer the first over the second. What am I doing wrong?


Solution

  • reinterpret_cast validates that it can re-interpret the underlying bit structure at compile time, and it sees that you're trying to change a LPARAM to int and doesn't like it.

    Try static_cast instead.

    Further information: LPARAM is defined as LONG_PTR which itself is:

    #if defined(_WIN64)
     typedef __int64 LONG_PTR; 
    #else
     typedef long LONG_PTR;
    #endif