Easily passing Managed strings to Unmanaged code (round 2)

My previous blog entry was about passing Managed strings to unmanaged code. Not being very interop-savy, I came up with a method and concluded there must be a better  way – and lots of people quickly let me know there was (especially Nicholas Allen, jiangsheng, Thomas Johansson, and Jochen Kalmbach).

 

You can do exactly this with PtrToStringChars (which is defined in vcclr.h). See here and msdn  for more details.  (Kudos to Nicholas Allen for being the first to point this out)

Since my method was so far off the mark, I took the post down to avoid some innocent developer stumble across it and try to use it.

 

jiangsheng also had a great comment on that post I wanted to repeat here:

From https://msdn.microsoft.com/library/en-us/dnvs05/html/movNETWFX.asp

C++/CLI comes with some helper templates, including auto_close<>, a variant on a smart pointer that calls the Close method of the instance it wraps, and marshal_as<>, which converts related types such as System::String and std::string.

String^ str = "Managed string";
SomeNativeFunction(marshal_as<char*>(str));

or you can write such template marshal functions yourself.

 

[update] I just got an update from jiangsheng:

I metioned this function in
https://blogs.msdn.com/jmstall/archive/2005/02/14/372454.aspx. But according to a post I read recently, marshal_as was cut from VS2005.
My replacement of this function can be found at https://blog.joycode.com/jiangsheng/archive/2005/03/19/46065.aspx