Marshalling stucts with bit-fields in C#

前端 未结 4 1943
死守一世寂寞
死守一世寂寞 2020-12-16 05:58

Is it possible to marshal a C-style struct containing bit-fields to a C# struct, or would you have to marshal it to a basic type and then do bit-masks?

E.g. I would

4条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-16 06:41

    Thats my "safe c#" port of a rgb16 struct.

    [StructLayout(LayoutKind.Explicit, Size = 2, Pack = 1)]
    public class Color16
    {
        // Btifield: 5
        [FieldOffset(0)]
        private ushort b_i;
    
        public ushort b
        {
            get { return (ushort)((b_i >> 11) & 0x1F); }
            set { b_i = (ushort)((b_i & ~(0x1F << 11)) | (value & 0x3F) << 11); }
        }
    
        // Bitfield: 6
        [FieldOffset(0)]
        private ushort g_i;
    
        public ushort g
        {
            get { return (ushort)((g_i >> 5) & 0x7F); }
            set { g_i = (ushort)((g_i & ~(0x7F << 5)) | (value & 0x7F) << 5); }
        }
    
        // Bitfield: 5
        [FieldOffset(0)]
        private ushort r_i;
    
        public ushort r
        {
            get { return (ushort) (r_i & 0x1F); }
            set { r_i = (ushort) ((r_i & ~0x1F) | (value & 0x1F)); }
        }
    
        [FieldOffset(0)]
        public ushort u;
    
        public Color16() { }
        public Color16(Color16 c) { u = c.u; }
        public Color16(ushort U) { u = U; }
    
    }
    

提交回复
热议问题