我仍在努力将一个相当复杂的结构从 C++ 编组到 C#。
C++中的结构体如下:
typedef struct {
DWORD Flags;
DWORD TimeCode;
DWORD NodeMoving;
Matrix NodeRots[NUM_GYROS];
Vector Position;
DWORD ContactPoints;
float channel[NUM_CHANNELS];
} Frame;
Vector:
typedef struct {
union {
struct {
float x, y, z;
};
float Array[3];
};
} Vector;
Matrix:
typedef struct {
union {
struct {
float xx, xy, xz; //This row is the right vector
float yx, yy, yz; //This row is the up vector
float zx, zy, zz; //This row is the forward vector
};
float Array[3][3]; //[row][col]
};
} Matrix;
这是我在 c# 中的内容:
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public unsafe struct Matrix
{
public float xx;
public float xy;
public float xz;
public float yx;
public float yy;
public float yz;
public float zx;
public float zy;
public float zz;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public unsafe struct Vector{
public float x;
public float y;
public float z;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public unsafe struct Frame{
public uint Flags;
public uint TimeCode;
public uint NodeMoving;
public fixed byte NodeRots[NUM_GYROS];
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);
return array;
}
}
}
public unsafe Matrix[] nodeRots{
get{
fixed (byte* ptr = NodeRots){
IntPtr ptr2 = (IntPtr)ptr;
Matrix[] array = new Matrix[NUM_GYROS];
for (int i = 0; i < array.Length; i++)
{
array[i] = (Matrix)Marshal.PtrToStructure(ptr2, typeof(Matrix));
IntPtr oldptr = ptr2;
ptr2 = new IntPtr(oldptr.ToInt32() + Marshal.SizeOf(typeof(Matrix)));
}
return array;
}
}
}
Frame 结构体的 Flags、TimeCode、NodeMoving 和 NodeRots 值已正确传递。成员位置、联系点和渠道未正确编组。我想我必须对职位成员做点什么,但我真的不知道到底错在哪里。