Alex Rivera | Logout

Help with \0 terminated strings in C#

Asked 2010-04-05T21:35:44.567
24

I'm using a low level native API where I send an unsafe byte buffer pointer to get a c-string value.

So it gives me

// using byte[255] c_str
string s = new string(Encoding.ASCII.GetChars(c_str));

// now s == "heresastring\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0(etc)";

So obviously I'm not doing it right, how I get rid of the excess?

Edit
Report

1 Answer

4

How about one of the System.Runtime.InteropServices.Marshal.PtrToString* methods?

Marshal.PtrToStringAnsi - Copies all characters up to the first null character from an unmanaged ANSI string to a managed String, and widens each ANSI character to Unicode.

Marshal.PtrToStringUni - Allocates a managed String and copies all or part to the first null of an unmanaged Unicode string into it.

answered 2010-04-05T22:00:11.910

Your Answer