0

I need to convert LPTSTR to String^ for be able to view it via MessageBox;

LPTSTR szResult;
DWORD language = GetPrivateProfileString(L"LANGUAGE", L"LANGUAGE", L"", szResult, 255, L"\\file.ini");
System::String^ str_buffed = msclr::interop::marshal_as<System::String^>(szResult);
MessageBox::Show("CLR MessageBox", str_buffed, MessageBoxButtons::OK, MessageBoxIcon::Exclamation);

Am I doing it in good way? Because I got en exception: System.AccessViolationException - Attempting to read the protected memory

How can I read in other way ini file and convert it (returns) to String^ ?

Narkon
  • 398
  • 2
  • 17
  • 1
    szResult should be defined as something like TCHAR szResult[501]; Access violation occurs because for an outbound parameter you are passing a pointer to an un-allocated memory location. – MNS Jan 20 '15 at 11:56
  • 1
    An AVE is *never* the "good way". The obvious bug is your szResult declaration, it needs to be a TCHAR[] and cannot be a LPTSTR. Lying with 255 should have made you uncomfortable *before* making this mistake. – Hans Passant Jan 20 '15 at 11:56
  • As for the explanation: LPTSTR is a pointer type (the "P" in the name). It doesn't allocate buffer memory. It isn't initialized, so it can point anywhere, most likely to nullptr. Chances are less than one in a million that your app said it is using the address in `szResult`. And if it did, you want something else at that memory location than what `GetPrivateProfileString` puts there (and good luck finding that bug). – starturtle Dec 11 '16 at 08:17

0 Answers0