Marshalling complex struct to c#

后端 未结 1 756
北海茫月
北海茫月 2021-01-15 07:51

i\'m still struggeling to marshal a quite complex struct from c++ to c#.

The struct in c++ is the following:

typedef struct {
    DWORD Flags;                


        
相关标签:
1条回答
  • 2021-01-15 08:29

    I have already told you. You can't use fixed byte as an universal solution to problems.

    This

    public fixed byte NodeRots[NUM_GYROS];
    

    must be

    public fixed Matrix NodeRots[NUM_GYROS];
    

    Then this:

    Marshal.Copy((IntPtr)ptr, array, 0, CHANNEL_ARRAY_SIZE)
    

    must be

    Marshal.Copy((IntPtr)ptr, array, 0, CHANNEL_ARRAY_SIZE * sizeof(float));
    

    Then for the nodeRots getter you don't really need the Marshal.PtrToStructure, because your struct can be marshaled directly.

    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
    public unsafe struct Frame
    {
        public uint Flags;
        public uint TimeCode;
        public uint NodeMoving;
        public fixed float nodeRots[NUM_GYROS * 9];
        public Vector Position;
        public uint ContactPoints;
        public fixed float channel[CHANNEL_ARRAY_SIZE];
    
        public unsafe float[] Channel
        {
            get
            {
                fixed (float* ptr = channel)
                {
                    float[] array = new float[CHANNEL_ARRAY_SIZE];
    
                    Marshal.Copy((IntPtr)ptr, array, 0, CHANNEL_ARRAY_SIZE * sizeof(float));
                    return array;
                }
            }
        }
    
        public unsafe Matrix[] NodeRots
        {
            get
            {
                fixed (float* ptr = nodeRots)
                {
                    Matrix[] array = new Matrix[NUM_GYROS];
    
                    for (int i = 0, y = 0; i < array.Length; i++, y += 9)
                    {
                        array[i].xx = ptr[y + 0];
                        array[i].xy = ptr[y + 1];
                        array[i].xz = ptr[y + 2];
    
                        array[i].yx = ptr[y + 3];
                        array[i].yy = ptr[y + 4];
                        array[i].yz = ptr[y + 5];
    
                        array[i].zx = ptr[y + 6];
                        array[i].zy = ptr[y + 7];
                        array[i].zz = ptr[y + 8];
                    }
    
                    return array;
                }
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题