JonaGik
JonaGik

Reputation: 1573

Converting between managed and unmanaged code

I was wondering if the following is valid for converting between a managed string and a standard string:

String ^ mymgdstring;
std::string mystdstring = *[PTR TO MYMGDSTRING, NOT SURE OF SYNTAX]

(i.e. create a std string which is equal to the dereferenced pointer to a managed string)

If this isn't valid, why not? What is the best method (i.e. most efficient) for converting between these?
Also, how do you get a pointer to a managed string?

Upvotes: 0

Views: 1354

Answers (2)

Ben Voigt
Ben Voigt

Reputation: 283961

A copy is necessary, because the .NET String data can be moved around during garbage collection.

You can assume marshal_as is the most efficient way to do this conversion. If a faster way is found, marshal_as will be updated to use it (it's a template and can be specialized).

You can get an interior pointer to the data of a System::String (it will be in Unicode, that's the internal format of .NET strings) using PtrToStringChars. To use it with native code, you must first pin the string by using pin_ptr instead of interior_ptr.

Upvotes: 1

Puppy
Puppy

Reputation: 147054

C++/CLI comes with a function called MarshalAs which can perform the conversion.

Upvotes: 0

Related Questions