Managed String To LPCSTR

B

Bragadiru

I want to read from an ini file :
System::String* windowsFolder = System::Environment::SystemDirectory;

System::String* iniFile = System::IO::path::Combine(windowsFolder,
"My.ini");

char Class[200];

LPCTSTR lstr = 0;

lstr = static_cast<LPCTSTR>(const_cast<void*>(static_cast<const
void*>(Marshal::StringToHGlobalAuto(iniFile))));

// I took this cast from MSDN->Managed Extensions for C++ Migration
Guide->Appendix: Sample Code

// iniFile is good = "C:\winnt\system32\My.ini", BUT lstr is only "C" ?!!!!

GetPrivateProfileString("Section", "Key", "", Class, 199, lstr);

Please help.

Thanks
 
T

Tomas Restrepo \(MVP\)

Bragadiru,
I want to read from an ini file :
System::String* windowsFolder = System::Environment::SystemDirectory;

System::String* iniFile = System::IO::path::Combine(windowsFolder,
"My.ini");

char Class[200];

LPCTSTR lstr = 0;

lstr = static_cast<LPCTSTR>(const_cast<void*>(static_cast<const
void*>(Marshal::StringToHGlobalAuto(iniFile))));

// I took this cast from MSDN->Managed Extensions for C++ Migration
Guide->Appendix: Sample Code

// iniFile is good = "C:\winnt\system32\My.ini", BUT lstr is only "C"
?!!!!

That's because in your use of StringToHGlobalAuto(), you're converting to a
wide char string, and storing the result in an ansi one (I bet you're not
compiling with UNICODE/_UNICODE defined).

Instead, use explicitly Marshal::StringToHGlobalAnsi() or STHGUni() as
necessary.
 
B

Bragadiru

It works. Thank you.

Tomas Restrepo (MVP) said:
Bragadiru,
I want to read from an ini file :
System::String* windowsFolder = System::Environment::SystemDirectory;

System::String* iniFile = System::IO::path::Combine(windowsFolder,
"My.ini");

char Class[200];

LPCTSTR lstr = 0;

lstr = static_cast<LPCTSTR>(const_cast<void*>(static_cast<const
void*>(Marshal::StringToHGlobalAuto(iniFile))));

// I took this cast from MSDN->Managed Extensions for C++ Migration
Guide->Appendix: Sample Code

// iniFile is good = "C:\winnt\system32\My.ini", BUT lstr is only "C"
?!!!!

That's because in your use of StringToHGlobalAuto(), you're converting to a
wide char string, and storing the result in an ansi one (I bet you're not
compiling with UNICODE/_UNICODE defined).

Instead, use explicitly Marshal::StringToHGlobalAnsi() or STHGUni() as
necessary.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top