Click to See Complete Forum and Search --> : cast StructLayout(LayoutKind::Explicit) to union


Kjetil
March 19th, 2003, 03:46 AM
Hello,

I have some "old" c-code that I wrapp inside a Managed C++ code. This code include a union.
I have created a new equal "union" in the wrapper class with StructLayout(LayoutKind::Explicit). So fare so good!

Then I want to call a function in the c-code with a parameter of the union type. A method in the Managed C++ code have a parameter of the "new union".

/* old c-code union */
typedef union {
double val_double;
int val_int;
h_time val_time;
INT64 val_longlong;
char val_string[8];
} h_anytype;

/* new Managed C++ union */
[ StructLayout(LayoutKind::Explicit) ]
public __value struct H_anytype {
[FieldOffset(0)] double val_double;
[FieldOffset(0)] int val_int;
[FieldOffset(0)] h_time val_time;
[FieldOffset(0)] INT64 val_longlong;
[FieldOffset(0)] char val_string __nogc[8];
};

/* the Managed C++ method calling the the c function */
void ClassX::MethodX(H_anytype *pars)
{
/*
* Do the call to the old c-code function
* - functionX(h_anytype *pars);
*/
functionX(pars);
}

How do I cast the Managed C++ code "union" to the "old" c-code union?

pareshgh
March 19th, 2003, 12:37 PM
You could use the union from C++ in C#.NET in following way.

Explaination:
The attributes play a key role in the layout of the structs in memory. How they are layout and memory bits and bytes etc.
you can customize the usage of structs to get the union of C++ working.

LayoutKind.Explicit plays significant role while converting the union. since in union a chunk of memory is allocated and finally who ever guy gets the part of that chunk can modify and change the layout. so it is really upto you how you want to change or how you want to handle it.

to illustrate this following is an example. of course you will need to use System.Runtime.InteropServices; for that. marshalling will require when necessary.





[StructLayout(LayoutKind.Explicit)] // most important
struct MyMemory
{
[FieldOffset(intvalue)] // needed
public int nCount;

[FieldOffset(intvalue)] // could change it as per req.
public float flt1;

... define char etc..
}

in above example these fields share the chunk of memory.

where intvalue starts from 0 as per your requirements.
for example you could replace first field with
[FieldOffset(4)]
public int nCount;

here FieldOffset is an attribute which is used to specify the layout of the field for the given struct.

Remember: struct are created on stack in memory.


Paresh