andriej
andriej

Reputation: 2266

converting System::String to wchar_t* - how is the end determined?

The process is explained here: http://msdn.microsoft.com/en-US/library/d1ae6tz5%28v=VS.80%29.aspx What I don't get from that article is that the pinned wchar_t* is passed to various C string functions that rely on the trailing null character. Is it a rule that .NET strings have a trailing null character? The System.String docs say that:

In the .NET Framework, a null character can be embedded in a string. When a string includes one or more null characters, they are included in the length of the total string.

Upvotes: 2

Views: 2583

Answers (2)

Boaz Yaniv
Boaz Yaniv

Reputation: 6424

From what I understand, the internal character buffer in .NET CLR strings is null-terminated, although naturally that null character doesn't make it into the character count, so any .NET code would ignore it. The only reason that null is there is for easy interop with Windows API or other plain C code that expects strings to be null-terminated. Instead of appending a null character any time a .NET string has to be passed to a C API (and possibly having to reallocate and copy the entire string), the null character is just there from the first place - a useful optimization in the real-world, since .NET still has to do a lot of interop behind the scenes, even if you don't use it explicitly.

If you do happen to have some null characters in the middle of your string, well, any C API that gets your string would probably stop there and never reach the end of the string. I guess you can even try it in C++/CLI yourself and see what happens. :)

Upvotes: 2

Mark Ransom
Mark Ransom

Reputation: 308206

Just guessing, because I don't have access to Microsoft internals.

It isn't explicitly stated, but a wchar_t* string should always be terminated with a null character. The example supports this, since it uses the printf_s function which depends on this characteristic.

The PtrToStringChars function is granting access to an internal string buffer. It is possible for the function to append a null character to the buffer without including it in the character count of the string, thus the .NET users of the string would not see the null.

Upvotes: 0

Related Questions