0

I have a structure definition in C++ as below

typedef struct { unsigned __int32 SetCommonPOP:1; unsigned __int32 SetCommonSVP:1; unsigned __int32 SetCommonUHDP:1; unsigned __int32 SetCommonMHDP:1; unsigned __int32 MinPwdLength:8; unsigned __int32 MaxPwdLength:8; unsigned __int32 StoredHdpBackups:8; } HPM_PWD_CONSTRAINTS; 

I translated that to c# as below

[StructLayout(LayoutKind.Explicit, Size=28, CharSet=CharSet.Ansi)] public struct HPM_PWD_CONSTRAINTS { [FieldOffset(0)] public uint SetCommonPOP; [FieldOffset(1)] public uint SetCommonSVP; [FieldOffset(2)] public uint SetCommonUHDP; [FieldOffset(3)] public uint SetCommonMHDP; [FieldOffset(4)] public uint MinPwdLength; [FieldOffset(12)] public uint MaxPwdLength; [FieldOffset(20)] public uint StoredHdpBackups; }; 

The code in c++ which I am converting to c# defines an object PWD of this structure and passes the value of an int x to this object.

*((uint*)&PWD) = x; 

How does this work? What would be the value of the structure object after this? How do I convert this to C#?

2
  • The first four uints in the struct should probably be bytes. Commented Oct 21, 2013 at 16:21
  • The first rule of SO is..... :P Commented Oct 21, 2013 at 16:24

2 Answers 2

1

The C++ structure is defining bits of a single 32-bit unsigned integer. The SetCommonPOP field is actually the least significant bit of the four byte structure.

You cannot convert this directly to C#, even with FieldOffset. Rather, treat the value as a uint and perform bit manipulation to read the separate fields.

Here's a link that should better explain bit fields in C++, http://msdn.microsoft.com/en-us/library/ewwyfdbe.aspx

Sign up to request clarification or add additional context in comments.

Comments

0

This code unsafely converts the struct pointer into a pointer to a uint, then writes the specified uint into that bit of memory.

This overwrites the first four bytes of overlapped fields to hold the value of the uint.

The equivalent C# code is exactly the same, within an unsafe method.
You could also simply set the SetCommonPOP field of the struct; since it's a uint the occupied the beginning of the struct, that would have the same effect.

2 Comments

@S Laks I edited the question. It was defined as uint in c++ which is why I left it as it is rather than using a byte for the first 4 members
When using FieldOFfset, are the members stored in memory from LSB to MSB? Is that why the first four members only get assigned? Also, in that case what would be the values of the remaining 3 members? 0?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.