Assign bit offset in a struct

  • Thread starter Thread starter J
  • Start date Start date
J

J

I'm interfacing with a C api (via Interop) which uses the following
typedef struct...

typedef struct _columnflags
{
BYTE bNoUpdate : 1;
BYTE bSetToNull : 1;
BYTE bDefault : 1;
} columnflags;

FYI: For those unfamiliar with this C/C++ syntax, the ": 1" specifies a
bit offset of 1 within the (8-bit) Byte. So bit 1 represents the
variable "bNoUpdate", bit 2 represents "bSetToNull", and bit 3
represents "bDefault". The remaining 5 bits are not used/referenced and
the total size of the structure is 1 Byte (8 bits).


I've been trying to declare this struct in VB.Net without success and
have had no luck researching news groups and other online resources.

In the meantime, I've tried approaches such as...

<StructLayout(LayoutKind.Sequential, Pack:=4, CharSet:=CharSet.Ansi)> _
Public Structure columnflags
Public bNoUpdate As Byte
Public bSetToNull As Byte
Public bDefault As Byte
End Structure

.... which just creates a structure of 3 Bytes instead 1 Byte with 3 bit
fields.

I've also tried...

<StructLayout(LayoutKind.Explicit, Size:=1, Pack:=4,
CharSet:=CharSet.Ansi)> _
Public Structure columnflags
<FieldOffset(1)> Public bNoUpdate As Byte
<FieldOffset(2)> Public bSetToNull As Byte
<FieldOffset(3)> Public bDefault As Byte
End Structure

....however, the FieldOffset attribute is specified in Bytes (not Bits).

Ideally, there would be an alternate attribute to FieldOffset that could
take in an argument representing the number of bits instead of number of
bytes.

If anyone has tackled a similar problem or has a solution to this I
would greatly appreciate it.

Thanks for your time. - J.
 
Pass the bit-packed struct as a single variable of type BYTE and use bit-and
and bit-or to test/set/clear the individual bits. AFIAK, the CLR has no
concept of a bit-sized field.

-cd
 
Back
Top