How to convert a structure to a byte array in C#?

前端 未结 14 818
难免孤独
难免孤独 2020-11-22 09:59

How do I convert a structure to a byte array in C#?

I have defined a structure like this:

public struct CIFSPacket
{
    public uint protocolIdentifi         


        
14条回答
  •  情深已故
    2020-11-22 10:13

    This can be done very straightforwardly.

    Define your struct explicitly with [StructLayout(LayoutKind.Explicit)]

    int size = list.GetLength(0);
    IntPtr addr = Marshal.AllocHGlobal(size * sizeof(DataStruct));
    DataStruct *ptrBuffer = (DataStruct*)addr;
    foreach (DataStruct ds in list)
    {
        *ptrBuffer = ds;
        ptrBuffer += 1;
    }
    

    This code can only be written in an unsafe context. You have to free addr when you're done with it.

    Marshal.FreeHGlobal(addr);
    

提交回复
热议问题