Equivalent in C# of Python's “struct.pack/unpack”?

前端 未结 3 2017
太阳男子
太阳男子 2021-01-12 05:25

I am a seasoned Python developer and have come to love a lot of its conveniences. I have actually known C# for some time but recently have gotten into some more advanced cod

3条回答
  •  余生分开走
    2021-01-12 06:16

    .NET (and thus, C#) has the Marshal.StructureToPtr and Marshal.PtrToStructure methods.

    You can abuse these to cast raw memory to a struct like you would in C, not that I'd recommend doing it this way (as it isn't exactly portable). You also need to get your Byte[] array buffer into the native heap in order to perform the operation on it:

    T FromBuffer(Byte[] buffer) where T : struct {
    
        T temp = new T();
        int size = Marshal.SizeOf(temp);
        IntPtr ptr = Marshal.AllocHGlobal(size);
    
        Marshal.Copy(buffer, 0, ptr, size);
    
        T ret = (T)Marshal.PtrToStructure(ptr, temp.GetType());
        Marshal.FreeHGlobal(ptr);
    
        return ret;
    }
    

提交回复
热议问题