简体   繁体   English

解引用指针C ++

[英]Dereferencing pointer C++

I just managed to write a global CBT hook in c++, usable with c#. 我只是设法用c ++编写了一个可用于c#的全局CBT钩子。 It may sound stupid but my knowledge of pointers and dereferencing of those is very bad due to my work with c#. 听起来可能很愚蠢,但是由于我使用c#的工作,所以我对指针的了解和对它们的取消引用非常糟糕。

I'm not able to dereference a pointer inside a struct pointed to by the lParam. 我无法在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. 看起来像这样:lParam是CBT_CREATEWND结构的长指针,该结构又持有成员“ lpcs”和CREATESTRUCT的指针。 This struct contains a member "x", which I want to read. 该结构包含一个成员“ x”,我想阅读该成员。 I tried the following, but I get invalid values for x: 我尝试了以下操作,但是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: 好吧,我真的不能说出为什么您会得到无效的x值的细节,但是我可能会以不同的方式编写这段代码:

// 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. 当您编写x->y ,它实际上与(*x).y相同,但是语法更好。

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. 您的语法似乎已签出,尽管可能有点LPCREATESTRUCT ,并且LPCREATESTRUCT显然是不必要的。

You mentioned that you get invalid values for x , perhaps lParam is not really a pointer to a CBT_CREATEWND structure? 您提到x值无效,也许lParam实际上不是指向CBT_CREATEWND结构的指针? Are you checking that nCode of the callback function is equal to HCBT_CREATEWND before casting lParam ? 您是否在强制转换lParam之前检查了回调函数的nCode是否等于HCBT_CREATEWND

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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