将托管字段值从托管代码传递到本机代码时,其结构字段值无效

时间:2011-08-18 23:21:41

标签: c# c++ dll

我遇到以下问题:

C ++代码:

typedef struct
{
   double x;
   double y;
   double z;
} XYZ;

double Sum(XYZ xyz)
{
  return xyz.x +xyz.y + xyz.z;
}

C#代码:

[StructLayout(LayoutKind.Sequential)]
public class XYZ
{
    public double x;
    public double y;
    public double z;
}
[DllImport("MyUnmanaged.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern double Sum([MarshalAs(UnmanagedType.LPStruct)] XYZ xyz);

当我按照C#main运行时:

XYZ1 xyz1 = new XYZ1 { x = 1f, y = 1f, z = 1f};
var x = MarchingCubesWrapper.Sum(xyz1);

我看到结构值没有很好地传递到非托管环境,这里是截图:

你能告诉我,问题是什么?

1 个答案:

答案 0 :(得分:2)

您需要将XYZ声明为struct而不是class。然后它应该正确编组。