Re: Passing arguments through messages
"Joseph M. Newcomer" <newcomer@flounder.com> wrote in message
news:gpe7b2t4mj5ir8beormg6vqjge8ehdotnt@4ax.com...
But why use some intermediate LPARAM variable? This is just gratuitous
Come on, Joe, you're just splitting hairs. The poster wanted to show that
you can allocate a structure, gets a pointer to it then pass the pointer.
Three lines of code show each step distinctly.
GetParent()->SendMessage(..., (LPARAM)&x);
is much simpler and avoids the unnecessary assignment and the conceptual
baggage that goes
with it.
I had presumed the parameters would be transient, and as you observe, the
pointer must not
be retained because it would be meaningless. If there was a need to
retain the pointer,
or to use PostMessage, then it would be necessary to allocate an object on
the heap, and
have the recipient delete it when it was no longer needed. PostMessage
works perfectly
well under those conditions, and the paradigm is quite common.
CString * s = new CString;
s->Format(...);
PostMessage(UWM_LOG_INFO, (WPARAM)s);
is a typical example of this, where the recipient does
LRESULT CMyWnd::OnLogInfo(WPARAM wParam, LPARAM)
{
CString * s = (CString *)wParam;
c_Log.AddString(*s);
delete s;
return 0;
}
as a typical exemplar of the model.
The thing is this code is all well and good so long as message source always
passes a pointer to CString. Isn't it better practise to let whoever did the
allocation also to do the deletion?
joe
On Tue, 11 Jul 2006 13:55:11 +0100, "David Webber"
<dave@musical.demon.co.uk> wrote:
"KMA" <kma@schneeberger.ch> wrote in message
news:e8vrk9$rqc$1@atlas.ip-plus.net...
Each message has two parameters, refered to as wParam and lParam. When
you
send the message you can give these values. They are simple 32 bit
values,
so you can't directly pass through much information. But some people use
them to store a pointer to a structure which contains much more
information. There are some caveats to this however concerning the
validity of the memory being pointed to.
I think the caveats are simple enough, and definitely worth mentioning!
If
you do
MyStruct x
...
LPARAM lParam = (LPARAM)(&x);
SendMessage( ....lParam );
....
then that is fine as long as the receiver doesn't try to store the pointer
it gets as the LPARAM for posterity. SendMessage causes the message to
be
handled and x hangs around while it is.
But PostMessage wouldn't be a good idea under any circumstances as x will
have been lost by the time the message is received and handled and the
pointer received as an LPARAM willl be meaningless.
Dave
Joseph M. Newcomer [MVP]
email: newcomer@flounder.com
Web: http://www.flounder.com
MVP Tips: http://www.flounder.com/mvp_tips.htm