Search code examples
c#.netmemory-managementstructlayout

Fixed sbyte[] to string C#


I'm trying to get a string from memory using StrucLayout and FieldOffset

But I'm having a lot of trouble understanding how byte works.

Here is my code ATM :

[StructLayout(LayoutKind.Explicit)]
public unsafe struct InfoDetails
{
    [FieldOffset(0x14)]
    public fixed sbyte Name[50];

    public string getName
    {
        get
        {
            fixed (sbyte* namePtr = Name)
            {
                return new string(namePtr);
            }
        }
    }
}

This code returns : T. Expected result is TEZ.

Any advices on why I'm doing it wrong ? Thanks


Solution

  • You could change the signature to:

    [FieldOffset(0x14)]
    public fixed char Name[25];
    
    public string getName
    {
        get
        {
            fixed (char* namePtr = Name)
            {
                return new string(namePtr);
            }
        }
    }
    

    Note how I changed sbyte to char and I halved the size of the buffer (because sizeof(char) == 2)

    Or you could even, more simply add a single cast to char*:

    fixed (sbyte* namePtr = Name)
    {
        return new string((char*)namePtr);
    }
    

    without changing anything else.