如何从C#中使用std :: vector作为参数调用非托管C ++函数?

如何从C#中使用std :: vector作为参数调用非托管C ++函数?

问题描述:

出于性能原因,我有一个C#前端和一个C ++后端。
现在,我想调用一个C ++函数,例如:

I have a C# front end and a C++ backend for performance reasons. Now I would like to call a C++ function like for example:

void findNeighbors(Point p, std::vector<Point> &neighbors, double maxDist);

我想要的是一个C#包装函数,例如:

What I'd like to have is a C# wrapper function like:

List<Point> FindNeigbors(Point p, double maxDist);

我可以将诸如Point []之类的平面数组传递给不受管理的C ++ dll,但是问题是,我不知道要分配多少内存,因为我不知道该函数将返回的元素数量...

I could pass a flat array like Point[] to the unmanaged C++ dll, but the problem is, that I don't know how much memory to allocate, because I don't know the number of elements the function will return...

是否有一种优雅的方法

感谢您的帮助!

Benjamin

这里最好的解决方案是用C语言编写包装函数,该函数仅限于非C ++类。通过PInvoke层[1],非平凡的C ++类基本上是不可拆的。而是让包装函数使用更传统的C签名,该签名易于P

The best solution here is to write a wrapper function in C which is limited to non-C++ classes. Non-trivial C++ classes are essentially unmarshable via the PInvoke layer [1]. Instead have the wrapper function use a more traditional C signature which is easy to PInvoke against

void findNeigborsWrapper(
  Point p,
  double maxDist, 
  Point** ppNeighbors,
  size_t* pNeighborsLength)

[1]是的,在某些情况下您可以摆脱它,但这是例外,而不是规则。

[1] Yes there are certain cases where you can get away with it but that's the exception and not the rule.