I have a small question about structures with the LayoutKind.Explicit
attribute set. I declared the struct
as you can see, with a fieldTotal
with 64 bits, being fieldFirst
the first 32 bytes and fieldSecond
the last 32 bytes. After setting both fieldfirst
and fieldSecond
to Int32.MaxValue
, I'd expect fieldTotal
to be Int64.MaxValue
, which actually doesn't happen. Why is this? I know C# does not really support C++ unions, maybe it will only read the values well when interoping, but when we try to set the values ourselves it simply won't handle it really well?
[StructLayout(LayoutKind.Explicit)]
struct STRUCT {
[FieldOffset(0)]
public Int64 fieldTotal;
[FieldOffset(0)]
public Int32 fieldFirst;
[FieldOffset(32)]
public Int32 fieldSecond;
}
STRUCT str = new STRUCT();
str.fieldFirst = Int32.MaxValue;
str.fieldSecond = Int32.MaxValue;
Console.WriteLine(str.fieldTotal); // <----- I'd expect both these values
Console.WriteLine(Int64.MaxValue); // <----- to be the same.
Console.ReadKey();
Defining a Unionunion Data { int i; float f; char str[20]; } data; Now, a variable of Data type can store an integer, a floating-point number, or a string of characters. It means a single variable, i.e., same memory location, can be used to store multiple types of data.
The members of structure and union in C can be objects of any type, such as other structures, unions, or arrays. Both structures or unions can be passed by value to a function and also return to the value by functions.
A structure can be nested inside a union and it is called union of structures. It is possible to create a union inside a structure.
We use the union keyword to define unions. Here's an example: union car { char name[50]; int price; }; The above code defines a derived type union car .
The reason is that FieldOffsetAttribute takes a number of bytes as parameter -- not number of bits. This works as expected:
[StructLayout(LayoutKind.Explicit)]
struct STRUCT
{
[FieldOffset(0)]
public Int64 fieldTotal;
[FieldOffset(0)]
public Int32 fieldFirst;
[FieldOffset(4)]
public Int32 fieldSecond;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With