2010-07-29 4 views
1

Supposons que nous avons deux C# structures:Comment transformer une structure C# en une autre comme en C++?

[Serializable, StructLayout(LayoutKind.Sequential, Pack = 1)] 
    public struct ByteStructure 
    { 
     public byte byte0; 
     public byte byte1; 
     public byte byte2; 
     public byte byte3; 
     public byte byte4; 
     public byte byte5; 
     public byte byte6; 
     public byte byte7; 
     public byte byte8; 
     public byte byte9; 
     public byte byteA; 
     public byte byteB; 
     public byte byteC; 
     public byte byteD; 
     public byte byteE; 
     public byte byteF; 
    } 

    [Serializable, StructLayout(LayoutKind.Sequential, Pack = 1)] 
    public struct IntStructure 
    { 
     public int i0; 
     public int i1; 
     public int i2; 
     public int i3; 
     } 

     ByteStructure bs; 
     IntStructure is; 
... 

Comment transformer une structure à l'autre comme en C++:

is = (IntStructure)bs; 

ou

bs = (ByteStructure)is; 

Répondre

3

La meilleure façon serait d'utiliser la classe Marshal et la mémoire non gérée.

static void Main(string[] args) 
    { 
     ByteStructure b = new ByteStructure(); 
     IntStructure i = new IntStructure(); 
     i.i0 = 0xa; 
     i.i1 = 0xb; 
     i.i2 = 0xc; 
     i.i3 = 0xd; 

     Debug.Assert(Marshal.SizeOf(typeof(IntStructure)) == Marshal.SizeOf(typeof(ByteStructure))); 

     IntPtr mem = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(IntStructure))); 
     Marshal.StructureToPtr(i, mem, false); 
     b = (ByteStructure)Marshal.PtrToStructure(mem, typeof(ByteStructure)); 
     Marshal.FreeHGlobal(mem); 

    } 
Questions connexes