2019-07-22 15:36

C# struct 轉換到 byte array

StructLayout: https://docs.microsoft.com/zh-tw/dotnet/api/system.runtime.interopservices.layoutkind?view=netframework-4.8
Pack: 資料欄位的對齊,這會影響最短欄位的 byte 長度

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]
public struct PollResponse
{
    public int AppId;
    public byte Serial;
    public short Station;
}


void Main()
{
    var data = new PollResponse
    {
        AppId = 1,
        Serial = 2,
        Station = 3,
    };

    Type type = typeof(PollResponse);
    int size = Marshal.SizeOf(type);
    var bytes = new byte[size];

    /* struct to byte array */
    IntPtr ptrIn = Marshal.AllocHGlobal(size);
    Marshal.StructureToPtr(data, ptrIn, true);
    Marshal.Copy(ptrIn, bytes, 0, size);
    Marshal.FreeHGlobal(ptrIn);

    BitConverter.ToString(bytes).Dump();
    /* 01-00-00-00 - 02 - 03-00 */


    /* byte array to struct */
    IntPtr ptrOut = Marshal.AllocHGlobal(size);
    Marshal.Copy(bytes, 0, ptrOut, size);
    var result = (PollResponse)Marshal.PtrToStructure(ptrOut, type);
    Marshal.FreeHGlobal(ptrOut);

    result.Dump();
    /* { AppId = 1, Serial = 2, Station = 3 } */
}

2 回應:

Jimmy 提到...

寫的簡單清楚 感謝

Jimmy 提到...
作者已經移除這則留言。