Obtenido de aqui
And about how to simulate C++ union in C# is described underneath:
In C++, Union expression is:
union UValue
{
char _cval;
int _ival;
double _dval;
};
And in C#, to apoint where the members'd be located in the memory space, we need to use StructLayoutAttribute, LayoutKind enum and FieldOffsetAttribute, which are all in the namespace System.Runtime.InteropServices.
Then, use struct to simulate the union above:
[StructLayout(LayoutKind.Explicit, Size=8)]
struct UValue
{
[FieldOffset(0)]
public char _cval;
[FieldOffset(0)]
public int _ival;
[FieldOffset(0)]
public double _dval;
}
As we know, every member of union's address starts with the same position of memory. By adding [FieldOffset(0)] to each member of UValue, we can make they share the same memory space. Of course, we must tell .NET that the distribution of these members is up to ourselves in advance by passing LayoutKind.Explicit to constructor of StructLayoutAttribute (then to UValue). In addition, explicitly set the size of UValue 8 bytes is optional. (in this case double which cost most needs 8 bytes)
No hay comentarios:
Publicar un comentario
escribe tu opinion: