我有 C# 类:
namespace Models
{
[StructLayout(LayoutKind.Explicit, Size = 120, CharSet = CharSet.Unicode)]
public struct DynamicState
{
[FieldOffset(0)]
public double[] Position;
[FieldOffset(24)]
public double[] Velocity;
[FieldOffset(48)]
public double[] Acceleration;
[FieldOffset(72)]
public double[] Attitude;
[FieldOffset(96)]
public double[] AngularVelocity;
}
}
和 C++/CLI 方法:
Models::DynamicState SomeClassClr::DoSomething(Models::DynamicState ds)
{
int struct_size = Marshal::SizeOf(ds);
System::IntPtr ptr = Marshal::AllocHGlobal(struct_size);
DynamicStateStruct ds_struct;
struct_size = sizeof(ds_struct);
Marshal::StructureToPtr(ds, ptr, false);
ds_struct = *(DynamicStateStruct*)ptr.ToPointer();
Models::DynamicState returnVal;
mpSomeClass->doSomething(ds_struct);
return returnVal;
}
其中 DynamicStateStruct 是本机 C++ 类:
struct DynamicStateStruct
{
double mPosition[3];
double mVelocity[3];
double mAcceleration[3];
double mAttitude[3];
double mAngularVelocity[3];
};
当我在本机 C++ 中恢复 struct ( ds_struct
) 时,我没有得到正确的值,我缺少什么想法?