c++winapisendmessagewm-copydata

How to cast a LRESULT to a custom struct type?


I use sendMessage and replyMessage to communicate between two apps in the same laptop. On the receiver side, when it receives the message comes from sender, it will reply with a message. So in the sender process, it will cast the MyStruct to LRESULT, send reply this to the sender app. I tried to cast it back in the receiver side, it also works.

    PCOPYDATASTRUCT result;
MyStruct* data;
LRESULT a;
MyStruct* t;
MyStruct* reply = new MyStruct;
switch (uMessageType)
{
case WM_COPYDATA:
    result = (PCOPYDATASTRUCT)addtionalData;
    data = (MyStruct*)result->lpData;

    reply->msgId = 10;
    strcpy_s(reply->msgInfo, 100, "test reply");
    a = reinterpret_cast<LRESULT>(reply);
    t = reinterpret_cast<MyStruct*>(a);//when cast the LRESULT data to MyStruct back here, it succeed

    ReplyMessage(reinterpret_cast<LRESULT>(reply));


    break;

However, when I was trying to cast this LRESULT to MyStruct in the sender side, it fails:

LRESULT result = SendMessage(test, WM_COPYDATA, (WPARAM)(HWND)hwndC, (LPARAM)(LPVOID)&data);
MyStruct* reply = (MyStruct*)result;//the value of reply is unreadable

How could I convert the LRESULT to my custom struct in the sender side ?

I just tried to send interger or float by the way. It works. However, if I use custom struct MyStruct, it won't work. I guess it is because the size of LRESULT is shorter than MyStruct.How to solve this problem ? The size of LRESULT is 4, size of int is also 4.

typedef struct msg{
int msgId;
char msgInfo[100];
}MyStruct;

Solution

  • When you send WM_COPYDATA, the data itself is copied to the receiving process.
    The receiver of WM_COPYDATA gets a pointer to this copy.
    It's very unlikely that the addresses are the same on both ends, but each end has a valid pointer to its own copy of the data.

    On the other hand, ReplyMessage does no such copying and only returns the (reinterpreted) address of the sender's data.
    This is not a valid address on the receiving end.

    If you want to pass data back and forth, you need to use SendMessage with WM_COPYDATA in both directions, possibly adding your own protocol on top.