C# array within a struct

前端 未结 5 1035
余生分开走
余生分开走 2020-12-01 10:59

Want to do this: (EDIT: bad sample code, ignore and skip below)

struct RECORD {
    char[] name = new char[16];
    int dt1;
}
struct BLOCK {
    char[] ver         


        
5条回答
  •  温柔的废话
    2020-12-01 11:23

    Use fixed size buffers:

    [StructLayout(LayoutKind.Explicit)]
    unsafe struct headerUnion                  // 2048 bytes in header
    {
        [FieldOffset(0)]
        public fixed byte headerBytes[2048];      
        [FieldOffset(0)]
        public headerLayout header; 
    }
    

    Alternativ you can just use the struct and read it with the following extension method:

    private static T ReadStruct(this BinaryReader reader)
            where T : struct
    {
        Byte[] buffer = new Byte[Marshal.SizeOf(typeof(T))];
        reader.Read(buffer, 0, buffer.Length);
        GCHandle handle = default(GCHandle);
        try
        {
            handle = GCHandle.Alloc(buffer, GCHandleType.Pinned);
            return (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T));
        }
        finally
        {
            if (handle.IsAllocated) 
                handle.Free();
        }
    }
    

提交回复
热议问题