c++结构体翻译为c#结构体

文章转自:http://social.msdn.microsoft.com/Forums/zh-CN/visualcshartzhchs/thread/8b050320-37b7-4bbf-90b6-b966eb48af24

 c++原结构体如下 :

  
  
  
  
  1. typedef     struct {                  /* CAN_MSG                      */ 
  2.     union { 
  3.         UINT8    id[4]; 
  4.         UINT32    identifier;     
  5.     }; 
  6.     union { 
  7.         struct { 
  8.             UINT8    length    :4;     /* data length                  */ 
  9.             UINT8    resbit    :2; 
  10.             UINT8    remote    :1;     /* remote transmission request  */ 
  11.             UINT8    format    :1;     /* frame format                 */ 
  12.         }; 
  13.         UINT8    info; 
  14.     }; 
  15.     UINT8    reserve[3]; 
  16.     UINT8    data[8];                  /* data field                   */ 
  17. } CAN_MSG; 
     

C#对应如下:

 

  
  
  
  
  1. using System.Runtime.InteropServices; 
  2.   
  3. public class CAN_MSG // CAN_MSG 
  4. //Unions are not supported in C#, but the following union can be simulated with the StructLayout and FieldOffset attributes. 
  5. //ORIGINAL LINE: union 
  6. //Structs must be named in C#, so the following struct has been named AnonymousStruct: 
  7.       [StructLayout(LayoutKind.Explicit)] 
  8.       public struct AnonymousStruct 
  9.       { 
  10.             [FieldOffset(0)] 
  11.             public byte[] id = new byte[4]; 
  12.             [FieldOffset(0)] 
  13.             public uint identifier; 
  14.       } 
  15. //Unions are not supported in C#. 
  16. //ORIGINAL LINE: union 
  17. //Structs must be named in C#, so the following struct has been named AnonymousStruct2: 
  18.       public struct AnonymousStruct2 
  19.       { 
  20. //Classes must be named in C#, so the following class has been named AnonymousClass: 
  21.             public class AnonymousClass 
  22.             { 
  23. //C# does not allow bit fields: 
  24.                   public byte length :4; // data length 
  25.                   public byte resbit :2; 
  26.                   public byte remote :1; // remote transmission request 
  27.                   public byte format :1; // frame format 
  28.             } 
  29.             public byte info; 
  30.       } 
  31.       public byte[] reserve = new byte[3]; 
  32.       public byte[] data = new byte[8]; // data field 

你可能感兴趣的:(C++,职场,C#,休闲)