将引用类型对象的数组从 C# 编组到 C++

Marshalling an array of reference type objects from C# to C++

通过使用 StructLayout(LayoutKind.Sequential)

装饰,我能够成功地将引用类型对象从 C# 传递到 C++

C#中的class:

StructLayout(LayoutKind.Sequential)
public class Point
{
        [DataMember]
        public double X { get; set; }
        [DataMember]
        public double Y { get; set; }
}

C++ 中的等价物:

struct Point
{
public:
    double x;
    double y;
};

C++中的函数体:

extern "C" __declspec(dllexport) void Translate(Point* pt, double dx, double dy)
{
    pt->x += dx;
    pt->y += dy;
}

和 C# 中的等价物:

[DllImport("myDll.dll", CallingConvention = CallingConvention.Cdecl)]
public extern static void Translate(Point pt, double dx, double dy); 

到目前为止我没有遇到任何问题,当我在接下来的 2 个函数之间传递这些点的数组时出现问题:

extern "C" __declspec(dllexport) double GetArea(Point** vertices,int count, bool isClosed)
    {
        double area = 0;
        if (!isClosed || count < 3) return 0;
        int j;
        for (int i = 0; i < count; i++)
        {
            // j = i+1 except when i = count then j = 0
            j = (i + 1) % count;

            area += vertices[i]->x * vertices[j]->y;
            area -= vertices[i]->y * vertices[j]->x;
        }
        area /= 2;
        return fabs(area);
    }

和 C# 版本:

[DllImport("myDll.dll", CallingConvention = CallingConvention.Cdecl)]
public extern static double GetArea(Point[] vertices, int count, bool isClosed);

是否有特定的方法来编组此数组?但保持 Point class 不变?

调用方法是这样的:

public static double GetArea()
        {
            Point[] vertices = { new Point(100, 100), new Point(0, 0), new Point(0, 100) };
            bool isClosed = true;
            return NativeMethods.GetArea(vertices, vertices.Length, isClosed); //this is the imported C++ method
}

你根本不应该互操作 类(明确支持的除外,例如 string、数组...)。 .NET 的本机互操作是为 C-style 函数和结构设计的,而不是 C++。因此,要么将本机代码更改为 C-style,要么使用 C++/CLI 之类的东西为 C++ 对象和函数提供托管接口。

处理互操作的最简单方法是使用编组器,并将 Point 更改为值类型,而不是引用类型:

struct Point
{
  public double x;
  public double y;
}

[DllImport("myDll.dll", CallingConvention = CallingConvention.Cdecl)]
public extern unsafe static double GetArea(Point[] vertices, int count, bool isClosed);

这当然需要 Point 成为可 blittable 类型 - 只需将其设为 struct 而不是 class 就足够了。当 vertices 是指向值数组的指针时,这就是您要做的全部。同样,您需要在 C++ 端使其成为一个值,而不是指针(函数的签名将是 GetArea(Point *vertices, ...),而不是使用指向指针的指针)。

手动编组数组有两个主要选项 - 不安全代码和 IntPtr。如果您需要编组更复杂的东西,这可能很有用

不安全签名很简单:

[DllImport("myDll.dll", CallingConvention = CallingConvention.Cdecl)]
public extern unsafe static double GetArea(Point** vertices, int count, bool isClosed);

创建和传递数组的方式与 C 中的方式相同 - 我无法真正提供任何具体内容,因为它完全取决于谁拥有什么内存,以及内存的结构。您可以轻松地使用现有的 .NET 数组,您只需要固定它们:

public static unsafe double CallGetArea(Point[] vertices, bool isClosed)
{
  if (vertices.Length == 0) throw new ArgumentException("Vertices empty.", "vertices");

  fixed (Point* pVertices = &vertices[0])
  {
    return GetArea(pVertices, vertices.Length);
  }
}

这假定您只想传递一个 Point 值的数组(签名将具有 Point*)。您不能真正将指针传递给这样的数组 - pVertices 是 read-only。同样,这仅在 Point 可 blittable 时有效。

IntPtr签名丢弃了类型信息:

[DllImport("myDll.dll", CallingConvention = CallingConvention.Cdecl)]
public extern unsafe static double GetArea(IntPtr vertices, int count, bool isClosed);

同样,该调用与 C 类似,您还必须执行许多烦人的编组器调用来读取和写入,而不是使用 C-like 语言来执行此操作。

如果您真的想坚持将指针指向 Point 的指针数组的想法,事情会变得有点复杂。编组器不支持指针数组,因此您必须手动进行编组。当然,这涉及大量不必要的复制和分配 - 所以如果您出于性能原因尝试这样做,请不要这样做。基本思路是这样的:

unsafe double CallGetAreaPointers(Point[] vertices, bool isClosed)
{
  var ipArray = Marshal.AllocHGlobal(vertices.Length * sizeof(Point));
  var ipItems = new Stack<IntPtr>();

  try
  {
    Point** pArray = (Point**)ipArray.ToPointer();

    for (var i = 0; i < vertices.Length; i++)
    {
      var ipItem = Marshal.AllocHGlobal(sizeof(Point));
      ipItems.Push(ipItem);

      Marshal.StructureToPtr(vertices[i], ipItem, false);

      pArray[i] = (Point*)ipItem.ToPointer();
    }

    GetArea(pArray, vertices.Length, isClosed);
  }
  finally
  {
    IntPtr ipItem;
    while ((ipItem = ipItems.Pop()) != IntPtr.Zero) Marshal.FreeHGlobal(ipItem);

    Marshal.FreeHGlobal(ipArray);
  }
}

(免责声明: 这只是一个 back-of-the-hand 代码;如果你决定这样做,请确保你做对了,这只是一个大概的想法)

请注意,为简单起见,我仍将 Point 用作 struct - 它只允许您在 C++ 端使用指针。如果您想完全使用并使其成为 C# 中的引用类型,最简单的方法是无论如何创建一个 PointStruct 类型(如果您愿意,请私有,这无关紧要)并复制 类 字段到结构。当然,在任何一种情况下,单独分配每个 Point 实例都没有什么意义——一个简单的值数组将以完全相同的方式工作,同时作为连续的内存位,使用起来更简单、更便宜,并且清理。