0

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?

Deduplicator
  • 44,692
  • 7
  • 66
  • 118
JonaGik
  • 1,533
  • 5
  • 24
  • 35
  • 1
    duplicates [this question](http://stackoverflow.com/questions/1300718/c-net-convert-systemstring-to-stdstring) – Eugene Jun 19 '11 at 12:22
  • @Eugene - I am aware that similar questions are asked all over the place and a quick Google search yields results but my question is specifically wondering about whether the method I showed is valid and what the most _efficient_ method is for doing the conversion (there seem to be a number of methods out there) because the application I'm writing amy be doing this conversion a lot – JonaGik Jun 19 '11 at 12:36
  • "equal" is going to be difficult, stuffing a utf-16 encoded Unicode string peg into a 8-bit std::string hole requires a big hammer. Your question is unanswerable unless you specify what kind of lossage you are willing to put up with. – Hans Passant Jun 19 '11 at 15:26

2 Answers2

1

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.

Ben Voigt
  • 277,958
  • 43
  • 419
  • 720
0

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

Puppy
  • 144,682
  • 38
  • 256
  • 465