multithreading - MFC/CLI mixed mode 'System.AccessViolationException' -
i running mfc dialog based application. have serial-comms thread running in reference class (outside code snippet) sends string^ dialog (so can put comms in window). problem (as see commented code) every time try string (except assign local variable) "an unhandled exception of type 'system.accessviolationexception' occurred in dlp_printer_control.exe
additional information: attempted read or write protected memory. indication other memory corrupt."
in snippet, atoi crashes. using atoi because had idea of trying copy each string element ascii , copying value member cstring. didn't work. every commented line produces exception. sue trying access originated in managed memory. workarounds suggested?
bool cdlp_printer_controldlg::updatecommswindow_right(string^ strcommsline) { cstring strtemp = strcommsline; lpwstr chartemp; int = 0; int i_len = strtemp.getlength(); if (i_len == 0) return false; chartemp= strtemp.getbuffer(i_len); =atoi((const char*)chartemp[0]); strtemp.releasebuffer(); //if (m_strcommsleft.isempty()) // return false; //lpctstr sztemp = (lpctstr)strtemp; //m_rightcommslabel.setwindowtextw((lpctstr)strtemp); //m_rightcommslabel.setwindowtextw(sztemp); //m_rightcommslabel.setwindowtextw(l"success"); return true; }
in snippet, atoi crashes.
i =atoi((const char*)chartemp[0]);
short answer chartemp[0]
tchar
, not pointer, while const char *
cast allows compile, value gets passed atoi
not pointer valid memory, causes system.accessviolationexception
exception. quick fix replace line i = _wtoi(chartemp);
, or i = _ttoi(strtemp);
discussed below.
lpwstr chartemp; /*...*/ chartemp= strtemp.getbuffer(i_len);
this compile if project built unicode. that's common case in windows nowadays, it's worth noting since mixing-in non-unicode functions atoi
later on. variation compile correctly both wide , narrow charsets, replace declaration charset-neutral lptstr chartemp;
.
i =atoi((const char*)chartemp[0]);
this compile if project not built unicode since atoi
expects plain old const char *
argument. charset-neutral ms mapping _ttoi, after dropping wrong [0]
, const char *
cast, code become i = _ttoi(chartemp);
.
finally, cstring
has built-in lpctstr
operator, there no need getbuffer/releasebuffer
, use intermediate lptstr chartemp;
. following same job in 1 step.
i = _ttoi(strtemp);
Comments
Post a Comment