Combining C ++ in C #

I am translating a library written in C ++ into C # and the keyword 'union' exists once. In structure.

What is the correct way to translate it to C #? And what is he doing? It looks something like this:

struct Foo { float bar; union { int killroy; float fubar; } as; } 
+59
c ++ c # unions
Sep 24 '08 at 12:20
source share
5 answers

You can use explicit fields for this:

 [StructLayout(LayoutKind.Explicit)] public struct SampleUnion { [FieldOffset(0)] public float bar; [FieldOffset(4)] public int killroy; [FieldOffset(4)] public float fubar; } 

untested. The idea is that two variables have the same position in your structure. Of course, you can use only one of them.

Additional information about unions in the struct tutorial

+63
Sep 24 '08 at 12:24
source share

You cannot decide how to handle this without knowing how it is used. If this is just used to save space, you can ignore it and just use a struct.

However, this usually does not mean that alliances are used. There are two general reasons for using them. One of them is to provide two or more ways to access the same data. For example, combining an int and an array of 4 bytes is one (of many) ways to extract bytes from a 32-bit integer.

Another is when the data in the structure comes from an external source, such as a network data packet. Typically, one element of a structure that spans a pool is an identifier that tells you which flavor of the pool is in effect.

In any of these cases, you cannot blindly ignore the union and transform it into a structure where two (or more) fields do not match.

+22
Sep 24 '08 at 15:37
source share

In C / C ++, union is used to superimpose different members in the same memory location, so if you have an int and flat union, they both use the same 4 bytes of memory, it is obvious that writing to one corrupts the other (since int and float have different bit layouts).

In .net, MS went with a safer choice and did not enable this feature.

EDIT: except interop

+3
Sep 24 '08 at 12:25
source share

Personally, I will ignore UNION together and implement Killroy and Fubar as separate fields

 public struct Foo { float bar; int Kilroy; float Fubar; } 

Using UNION saves 32 bits of memory allocated int .... is not going to make or interrupt the application these days.

+2
Sep 24 '08 at 12:34
source share

If you use union to map the bytes of one type to another, and then in C #, you can use BitConverter instead.

 float fubar = 125f; int killroy = BitConverter.ToInt32(BitConverter.GetBytes(fubar), 0); 

or

 int killroy = 125; float fubar = BitConverter.ToSingle(BitConverter.GetBytes(killroy), 0); 
0
Sep 21 '16 at 10:47
source share



All Articles