Reputation: 1552
I've been trying to get this to work for like ages but with no avail (sad face).
int iChars = GetWindowTextLength (GetDlgItem(handle,ID))+1; // Room for '\0'
char* pstrText;
pstrText = (char*) malloc (sizeof(char)*iChars);
if (pstrText != NULL) {
//GetWindowText (GetDlgItem(handle,ID), pstrText, iChars);
GetDlgItemText(handle,ID,pstrText,iChars);
}
return pstrText; // Memory gets freed after it returns
Working example:
char* MWC::System::TextBox::GetText(){
int len = SendMessage(handle, WM_GETTEXTLENGTH, 0, 0);
char* buffer = new char[len];
SendMessage(handle, WM_GETTEXT, (WPARAM)len+1, (LPARAM)buffer);
return buffer;
}
Upvotes: 3
Views: 18261
Reputation: 612794
The wParam
parameter is wrong here:
SendMessage(handle, WM_GETTEXT, (WPARAM)len, (LPARAM)buffer);
You should pass len+1
because of the zero-terminator.
Upvotes: 7
Reputation: 166
You are freeing the memory before returning!!!
if ((pstrText != NULL) {
GetDlgItemText(handle,ID,pstrText,sizeof(pstrText));
free (pstrText); // Freeing memory Here!
}
You must provide a way for the client to free when its no longer needed...
Hope this helps!
Upvotes: 3
Reputation: 1117
You already free the memory pointed to by pstrText
before you return. You should return a string object that can actually contain the text and frees it automatically on release. Or you'll have to ask the caller to allocate memory for the string, but then you are just wrapping the API.
Upvotes: 2