Sergey Kucher
Sergey Kucher

Reputation: 4180

Invalid Struct field values when passing it from managed to native code

I have a following problem:

C++ code:

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

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

C# code:

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

When I run following C# main:

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

I see that struct values did not passed to unmanaged environment well here is screenshot:

Could you tell me please what is the problem?

Upvotes: 1

Views: 141

Answers (1)

dlev
dlev

Reputation: 48606

You need to declare XYZ as a struct rather than a class. It should then marshal correctly.

Upvotes: 2

Related Questions