开发者

Dereferencing pointer C++

I just managed to write a global CBT hook in c++, usable with c#. It may sound stupid but my knowledge of pointers and dereferencing of those is very bad due to my work with c#.

I'm not able to dereference a pointer inside a struct pointed to by the lParam.

It looks like this: the lParam is a long Pointer to a CBT_CREATEWND struct, which in turn holds a member "lpcs", and a pointer to a CREATESTRUCT. This struct contains a member "x", which I want to read. I tried the following, but I get invalid values for x:

CREATESTRUCT str = *(LPCREATESTRUCT)(((LPCBT_CREATEWND)lParam开发者_运维问答)->lpcs);
int normal = str.x;
PostMessage(FindWindow(NULL, L"Process Watcher Window"), RegisterWindowMessage(L"ALEXX_SEINE_WNDMESSAGE_C"), wParam, normal);

could someone please help me?


Well I can't really speak towards the fine details of why you get invalid x values, but I would likely write this code differently:

// the way you had it, it was making a copy of the CREATESTRUCT and storing it in str
// this just uses a pointer
LPCREATESTRUCT str = ((LPCBT_CREATEWND)lParam)->lpcs;
// when you have a pointer, use -> to use a member
int normal = str->x;

Since you said you are new to pointers, I'll explain -> a bit. When you write x->y, it is really the same as (*x).y but with nicer syntax.

Also a note of advice, while the casts in this code seem reasonable. In general, if you find that you are casting a lot, you probably are doing it either the hard way, or the wrong way. So make sure you take the time to understand any casts that you do.


Your syntax seems to check out, even though it is perhaps a bit unreadable, and the LPCREATESTRUCT cast is obviously unnecessary.

You mentioned that you get invalid values for x, perhaps lParam is not really a pointer to a CBT_CREATEWND structure? Are you checking that nCode of the callback function is equal to HCBT_CREATEWND before casting lParam?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜