Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing 'this' pointer as LPARAM

I have as class as follows:

#include <Windows.h>
class MyClass
{
   void A();
   static BOOL CALLBACK proc(HWND hwnd, LPARAM lParam);
};

void MyClass::A()
{
   EnumChildWindows(GetDesktopWindow(), MyClass::proc, static_cast<LPARAM>(this));
}

BOOL CALLBACK MyClass::proc(HWND hwnd, LPARAM lParam)
{
   // ...
   return TRUE;
}

When I attempt to compile this in Visual C++ 2010, I get the following compiler error:

error C2440: 'static_cast' : cannot convert from 'MyClass *const ' to 'LPARAM' There is no context in which this conversion is possible

If I change the definition of MyClass::A as follows, then the compile succeeds:

void MyClass::A()
{
   EnumChildWindows(GetDesktopWindow(), MyClass::proc, (LPARAM)this);
}

What is the explanation for the error in the first example?

like image 954
JBentley Avatar asked Jul 29 '26 13:07

JBentley


2 Answers

You need to use a reinterpret_cast not a static_cast to perform a cast to a completely unrelated type. See this When should static_cast, dynamic_cast, const_cast and reinterpret_cast be used? for more details on the different types of C++ casts.

like image 185
shf301 Avatar answered Jul 31 '26 04:07

shf301


static_cast is used to cast related types, such as int to float, and double to float, or conversions which need too little effort, such as invoking single-parameter constructor, or invoking a user-defined conversion function.

LPARAM and this are pretty much unrelated, so what you need is reinterpret_cast:

LPARAM lparam =  reinterpret_cast<LPARAM>(this);
EnumChildWindows(GetDesktopWindow(), MyClass::proc, lparam);
like image 42
Nawaz Avatar answered Jul 31 '26 02:07

Nawaz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!