2

To convert from a system::String to an std::string, I use the following code:

IntPtr p = Marshal::StringToHGlobalAnsi(PORT);
string newString = static_cast<char*>(p.ToPointer());
Marshal::FreeHGlobal(p);

However, the place where I got the code uses

IntPtr p = Marshal::StringToHGlobalAnsi(PORT);
char* newString = static_cast<char*>(p.ToPointer());
Marshal::FreeHGlobal(p);

For some reason though, I get garbage in newString if I do the char* version. Anyone know why this would happen?

Thanks.

2 Answers 2

4

The reason the std::string version works is because it immediately creates a privatecopy of the char* value. This private copy is not affected by the later FreeHGlobal.

The char* version is assigned a pointer to memory which you then free on the very next line. It's invalid the moment the FreeHGlobal command executes.

Sign up to request clarification or add additional context in comments.

Comments

0

you can Returns a pointer to an array that contains a null-terminated sequence of characters with std::string::c_str then initialize the String^ with the char array

std::string bla = "ConvertMe";
String^ ResultString= gcnew String(bla.c_str());

1 Comment

While this piece of code may provide a solution to the question, it's better to add context as to why/how it works. This can help future users learn and eventually apply that knowledge to their own code. You are also likely to have positive feedback/upvotes from users, when the code is explained.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.