c# - 从托管代码传递到 native 代码时结构字段值无效

标签 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);

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

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

最佳答案

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

关于c# - 从托管代码传递到 native 代码时结构字段值无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7115316/

相关文章:

c# - 在 C++ 中使用非常 C# 的 DLL

c# - Linq to SQL 简单问题

c# - float 据类型的 Convert.ToSingle()

c# - 使用 Fluent api 进行 3 种方式的多对多

c++ - std::string 数组的初始值设定项太多

c++ - 在函数内部使用声明函数?

c# - 在 silverlight 中使用 WCF CloseAsync

c++ - 从 unique_ptr 返回原始指针是否正确?

c++ - 为什么我们需要在 Windows C++ 中链接 kernel32.dll、user32.dll 等...?

c - 在 Visual Studio 中用 C(不是 C++)编写一个 dll 导致无法解析的符号