Archived

This topic is now archived and is closed to further replies.

wing_majin

casting to LPARAM

Recommended Posts

wing_majin    122
I''ve got a listbox I fill as such: int index = SendDlgItemMessage(hwnd, IDC_LIST, LB_ADDSTRING, 0, (LPARAM)str.c_str()); SendDlgItemMessage(hwnd, IDC_LIST, LB_SETITEMDATA, (WPARAM)index, (LPARAM)str.c_str()); Where str is a std::string. The first works fine, and the string is displayed. The second, where I attempt to set the internal value of that element, doesn''t seem to take. It works however if I use a literal string like (LPARAM)"string". It fills properly and I can retrieve it later with an LB_GETITEMDATA message. Yet when I use c_str() or even manually convert the string to just char * and attempt to cast it doesn''t work either. How can this work fine in one line and not in the next? Isn''t it the same exact cast?

Share this post


Link to post
Share on other sites
Beer Hunter    712
The LB_SETITEMDATA message sets a 32-bit value (in this case, you''re using it to store a pointer) — it has no concept of a string. If you use it with a std::string, and that std::string subsequently goes out of scope, then the pointer you stored now points to unused memory.

Share this post


Link to post
Share on other sites
wing_majin    122
I thought std::string.c_str() returns const char *, it always works for everything else that needs a normal c-string. Besides, it still works fine in the first line.

Share this post


Link to post
Share on other sites
Beer Hunter    712
c_str() does return a const char*. However, that const char* stops being valid if you perform any non-const operation on the corresponding std::string.

The first line works because LB_ADDSTRING understands the concept of a string; Windows makes its own copy. LB_SETITEMDATA is different: it stores an integer, not a string.

Share this post


Link to post
Share on other sites