Pergunta

I'm adding a bunch of items to a treeview, with a string stored in lParam, like this:

TVITEM tvi = {sizeof(TVITEM)};
tvi.mask = TVIF_TEXT | TVIF_PARAM;
tvi.pszText = const_cast<char *> (txt0.c_str());  // Display text
tvi.cchTextMax = sizeof(tvi.pszText);
tvi.lParam = (LPARAM) add0.c_str();  // A file path string

TVINSERTSTRUCT tvis;
tvis.item = tvi;
tvis.hParent = hti0;  // Some parent node

TreeView_InsertItem(tvw_filelist_, &tvis);

After I finish adding all of them, I come back and check (in a different function):

TVITEM tvi = {sizeof(TVITEM)};
char buf[200];
tvi.pszText = buf;
tvi.cchTextMax = 200;
tvi.hItem = htiTemp;  // htiTemp is the current node in the iteration
tvi.mask = TVIF_TEXT | TVIF_PARAM;

// Retrieve; address is stored in lParam.
TreeView_GetItem(tvw_filelist_, &tvi);

char out[200];
strcpy(out, "Checking: PSZTEXT: ");
strcat(out, tvi.pszText);
strcat(out, ". LPARAM: ");
strcat(out, (const char *) tvi.lParam);

...and the LPARAM has been reset to the value of the last item added.

So, if I add items one, two, three, four with similar lParam values, then after I check they all have lParam of four. (Sometimes, there's garbage values.)

There's obviously a problem here, and it's probably really easy to fix, but after several hours of experimenting I can't find what's wrong. Help!

Foi útil?

Solução

tvi.lParam = (LPARAM) add0.c_str(); this is the problem. tvi.lParam is a pointer type.

FROM MSDN :

LPARAM This type is declared in WinDef.h as follows: typedef LONG_PTR LPARAM;

what is a add0? I guess it is a local variable. If the function return, this add0 var will be deconstructed, and tvi.lParam is pointed to the inter buff of string add0, and now this inter buff is freed, so tvi.lParam points to the garbage.

Outras dicas

You are storing an address in tvi.lParam. This is the address of the string add0.

If add0 goes out of scope then the address becomes invalid. This is the reason you see different values.

You must assign tvi.lParam an address which is always available. Make the string a global variable or class member variable.

Again, you will need one string for each tree node. So you will need to maintain an array of strings. If you have only one string then the same address will have a different value, like you are observing in case of one, two, three, four.

Thanks.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top