在C#中使用位域编组结构 [英] Marshalling stucts with bit-fields in C#
本文介绍了在C#中使用位域编组结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以将包含位域的C样式结构封送为C#结构,还是必须将其封存为基本类型然后再进行位掩码?
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?
例如我想从这样的C样式结构中进行封送:
E.g. I would like to marshal from a C style structure like this:
struct rgb16 {
unsigned int R : 4;
unsigned int G : 5;
unsigned int B : 4;
}
将其编组到这样的东西上:
And marshal it onto something like this:
[StructLayout(LayoutKind.Sequential)]
public struct Rgb16 {
public byte R;
public byte G;
public byte B;
}
推荐答案
C#中没有位域.因此,我将使用封装一点点摆弄的属性:
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;
}
}
我避免添加setter,因为我喜欢不可变的结构,但原则上您也可以添加它们.
I've avoided adding setters, because I like immutable structs, but in principle you can add them too.
这篇关于在C#中使用位域编组结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文