0
votes

I have a program that receives network packets that are binary serialized. I currently have a way of storing the data directly from the byte array into the struct by way of using pointers. But what I need now is a way to store UTF strings in the struct as well whilst still maintaining the easy method of copying from the byte array. The string is assumed to be prefixed with an unsigned short indicating the length in bytes of the string. Is this how C# internally stores char[] or strings or do I need to make my own struct to store it in?

My current struct layout is like this:

public struct GenericPacket
{
    public short packetid;

    public static GenericPacket ReadUsingPointer(byte[] data)
    {
        unsafe
        {
            fixed (byte* packet = &data[0])
            {
                return *(GenericPacket*)packet;
            }
        }
    }
}

Read using pointer simply takes a byte array and returns a pointer to it but as a GenericStruct. This works for every normal types, but strings are more complex.

Thanks for any ideas!

3

3 Answers

0
votes

That is a BSTR and BSTR methods would work on it (available in Win32 and Win32 compatability libraries) - if your prefix refers to the bytes, not the character count, since characters can be multiple bytes; BSTR doesn't know about any of that.

C-string is null-terminated with no prefix, C++ and C# strings use implementation-defined storage, although they generally use an array with a separate length parameter. They're definitely not BSTRs.

0
votes

You can use the System.Text.Encoding.GetString(byte[]) or System.Text.Encoding.UTF8.GetString(byte[]) that will return a string

0
votes

You can construct a string from char[] like this

char[] foo = new char[] {'a','b','c','d'}
string bar = new string(foo);

Combine this with a ranged array copy to extract a string from a larger block of bytes.

I believe this is what System.Text.Encoding.GetString(byte[] data, int start, int length) actually does internally, but in the .NET Micro Framework this is not available so you have to spell it out.