我一直试图让这个工作适合年龄但没有用(悲伤的脸)。
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
工作示例:
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;
}
答案 0 :(得分:7)
此处wParam
参数错误:
SendMessage(handle, WM_GETTEXT, (WPARAM)len, (LPARAM)buffer);
由于零终结符,您应该传递len+1
。
答案 1 :(得分:3)
你在回来之前释放内存!!!
if ((pstrText != NULL) {
GetDlgItemText(handle,ID,pstrText,sizeof(pstrText));
free (pstrText); // Freeing memory Here!
}
当客户不再需要时,您必须为客户提供免费的方式......
希望这有帮助!
答案 2 :(得分:2)
在您返回之前,您已释放pstrText
指向的内存。您应该返回一个实际上可以包含文本的字符串对象,并在发布时自动释放它。或者你必须要求调用者为字符串分配内存,但是你只需要包装API。