Marshalling stucts with bit-fields in C#

前端 未结 4 1950
死守一世寂寞
死守一世寂寞 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:59

    There are no bit-fields in C#. So I'd go with properties that encapsulate the bit fiddling:

    [StructLayout(LayoutKind.Sequential)]
    public struct Rgb16 {
        private readonly UInt16 raw;
        public byte R{get{return (byte)((raw>>0)&0x1F);}}
        public byte G{get{return (byte)((raw>>5)&0x3F);}}
        public byte B{get{return (byte)((raw>>11)&0x1F);}}
    
        public Rgb16(byte r, byte g, byte b)
        {
          Contract.Requires(r<0x20);
          Contract.Requires(g<0x40);
          Contract.Requires(b<0x20);
          raw=r|g<<5|b<<11;
        }
    }
    

    I've avoided adding setters, because I like immutable structs, but in principle you can add them too.

提交回复
热议问题