如何将一个C#结构转换为另一个C ++结构?

时间:2010-07-29 08:42:30

标签: .net winapi interop

假设我们有两个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;
...

如何在C ++中将一个结构转换为另一个结构:

is = (IntStructure)bs;

bs = (ByteStructure)is;

1 个答案:

答案 0 :(得分:3)

最简单的方法是使用Marshal类和非托管内存。

    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);

    }