views:

16

answers:

2

The goal is to avoid copying the string data when I need a const wchar_t*.

The answer seems to be yes, but the function PtrToStringChars doesn't have its own MSDN entry (it's only mentioned in the KB and blogs as a trick). That made me suspicious and I want to check with you guys. Is it safe to use that function?

A: 

Yes, no problem. It is actually somewhat documented but hard to find. The MSDN docs for the C++ libraries aren't great. It returns an interior pointer, that's not suitable for conversion to a const wchar_t* yet. You have to pin the pointer so the garbage collector cannot move the string. Use pin_ptr<> to do that.

You can use Marshal::StringToHGlobalUni() to create a copy of the string. Use that instead if the wchar_t* needs to stay valid for an extended period of time. Pinning objects too long isn't very healthy for the garbage collector.

Hans Passant
I wouldn't recommend `StringToHGlobalUni`. Using `PtrToStringChars` and then making a copy yourself could be quite a bit faster than messing with HGLOBAL, which is a specialized allocator with limited practical use. Actually `marshal_as<BSTR>` or `marshal_as<std::wstring>` would be by recommendations for a native copy. http://msdn.microsoft.com/en-us/library/bb384865.aspx
Ben Voigt
A: 

According to this article: http://support.microsoft.com/kb/311259 PtrToStringChars is officially supported and may be used. It is described as "get an interior gc pointer to the first character contained in a System::String object" in vcclr.h .

Alex Farber