将指针'this'传递为 LPARAM

Passing 'this' pointer as LPARAM

本文关键字:LPARAM this 指针      更新时间:2023-10-16

我有如下类:

#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;
}

当我试图在Visual C++2010中编译它时,我得到了以下编译器错误:

错误C2440:"static_cast":无法从"MyClass*const"转换为"LPARAM"没有任何上下文可以实现这种转换

如果我按如下方式更改MyClass::A的定义,则编译成功:

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

对第一个例子中的错误有什么解释?

您需要使用reinterpret_cast而不是static_cast来执行到完全不相关类型的强制转换。请参阅以下内容:何时应使用static_cast、dynamic_cast、const_cast和relpret_cast?有关不同类型的C++类型转换的更多详细信息。

static_cast用于强制转换相关类型,如intfloatdoublefloat,或需要太少工作的转换,如调用单参数构造函数或调用用户定义的转换函数。

LPARAMthis几乎不相关,所以您需要的是reinterpret_cast:

LPARAM lparam =  reinterpret_cast<LPARAM>(this);
EnumChildWindows(GetDesktopWindow(), MyClass::proc, lparam);

如您所知,此指针是const,static_cast运算符不能丢弃constvolatile__unaligned属性。看看MSDN上的这个链接。