tags:

views:

178

answers:

4

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?

A: 

I believe \0 is "null" in ascii -- are you sure the string you're getting is actually ascii encoded?

Jason M
I think he means that he's getting a series of null bytes, not that he's actually getting the "\0" string sequence.
Randolpho
Yes, it's ASCII
Joshua
I guess I'll do like .Trim("\0") haha
Joshua
Heh... `Trim` works too. :)
Randolpho
A: 

There may be an option to strip NULs in the conversion.

Beyond that, you could probably clean it up with:

s = s.Trim('\0');

...or, if you think there may be non-NUL characters after some NULs, this may be safer:

int pos = s.IndexOf('\0');  
if (pos >= 0)
    s = s.Substring(0, pos);
Jason Williams
+2  A: 

.NET strings are not null-terminated (as you may have guessed from this). So, you can treat the '\0' as you would treat any normal character. Normal string manipulation will fix things for you. Here are some (but not all) options.

s = s.Trim('\0');

s = s.Replace("\0", "");

var strings =  s.Split(new char[] {'\0'}, StringSplitOptions.RemoveEmptyEntries);
John Fisher
A: 

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

OldFart