Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I simulate a C++ union in C#?

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();
like image 592
devoured elysium Avatar asked Jul 21 '09 23:07

devoured elysium


People also ask

How do you declare a union in C?

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.

Can a function return a union in C?

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.

Can we use union inside structure in C?

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.

What is union in C with example?

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 .


1 Answers

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;
}
like image 189
Ben M Avatar answered Sep 28 '22 06:09

Ben M