How to send struct or pointer using SendMessage or PostMessage function?
2 Answers
Here is simple example:
typedesf struct tagMY_STRUCT{
unsigned int a;
unsigned int b;
unsigned int c;
}MY_STRUCT;
//Some code which sends message
MY_STRUCT *pStruct = new MY_STRUCT;
pStruct->a = 5;
pStruct->b = 4;
pStruct->c = 1;
SendMessage(hWnd, WM_USER + 1, 0, (LPARAM)pStruct);
//WndProc
case (WM_USER + 1) :
{
MY_STRUCT *pStruct = (MY_STRUCT*)lParam);
if(pStruct)
{
int a = pStruct->a;
delete pStruct;
}
}
break;
Don't ever try to do it between processes.Study IPC basics first.
Don't forget to release pointer to struct once not needed using delete.
UPDATE
As Remy Lebeau mentioned in comment, you can also allocate struct on stack instead on heap using new/malloc, because SendMessage block thread until it's processed in WndProc.This does not apply to PostMessage which add message to window's message queue and return immediately, so it requires heap block.
However, if you plan to pass more complex data struct I recommend heap allocation instead of stack.
13 Comments
SendMessage() is synchronous, so you don't need to use new to allocate the struct dynamically. You can allocate it on the stack instead and just pass its pointer to SendMessage(). The receiver does not need to free it. PostMessage(), on the other hand, is asynchronous, so the new/delete approach is necessary.SendMessage(), the receiver should not free the memory, the sender should after SendMessage() exits.Send/Post it to where?
In general, an in-process communication by casting a pointer to LParam or WParam at one end and casting it back at the other is fairly straightforward. Don't create objects/structs/whatever on local stacks, especially when PostMessaging - use dynamic allocation with new(). Consider the object lifetime - if the receiver does not need to keep a PostMessaged object or pass it on, it should delete() it.
For inter-process comms, Google for 'WM_COPYDATA'.