本文介绍了使用 c# 的 StrucLayout 和 FieldOffset 表示联合位域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道为了在 C# 中表示联合,我需要使用 StructLayout[LayoutKind.Explicit)] 和 [FieldOffset(x)] 属性来指定联合内部的字节偏移量.但是,我有一个以下联合我想表示,而 FieldOffset 属性仅按字节大小偏移.

I understand that in order to represent unions in C# I need to use StructLayout[LayoutKind.Explicit)] and [FieldOffset(x)] attribut to specify the byte offset inside the union. However, I have a following union I want to represent and FieldOffset attrib only offset by size of a byte.

union _myUnion
{
     unsigned int info;
     struct
     {
          unsigned int flag1:1 // bit 0
          unsigned int flag2:1 // bit 1
          unsigned int flag3:1 // bit 2
          unsigned int flag4:1 // bit 3
          unsigned int flag5:1 // bit 4
          unsigned int flag6:1 // bit 5
          .
          .
          .
          unsigned int flag31:1 // bit 31
     }
}

正如您在联合中的内部结构中看到的那样,我不能使用 FieldOffset,因为我需要一些可以稍微偏移的东西.

As you can see for the inner struct in the union, I can't use FieldOffset since I need something that can offset by a bit.

有没有办法解决这个问题?我正在尝试调用一个 DLL 函数,其中一个数据结构被定义为这样,我对如何最好地表示这个联合结构没有想法.

Is there a solution to this? I am trying to call a DLL function and one of the data struct was defined as such and I ran out of ideas on how to best represent this union struct.

推荐答案

那里不需要联合;数据的一个字段+属性,8个做按位移位"操作的属性,例如:

No need for union there; one field+property for the data, 8 properties that do bitwise "shift" operations, for example:

public uint Value {get;set;}

public uint Flag2 {
   get { return Value >> 2; }
}

等等.我还以为你想要 bool 在这里?

etc. I would also have thought you want bool here?

通常我会说:不要制作可变结构.PInvoke 可能(我不确定)是一个有效的场景,所以我会忽略它:)

Normally I'd say: don't make mutable structs. PInvoke may (I'm not sure) be a valid scenario for that, so I'll ignore it :)

如果该值确实使用了 32 位以上,请考虑将支持字段切换为 ulong.

If the value is genuinely using more than 32 bits, consider switching the backing field to ulong.

这篇关于使用 c# 的 StrucLayout 和 FieldOffset 表示联合位域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 15:23