c# - 如何将 vector<int> 从 C++ dll 编码到 C# 应用程序?

标签 c# .net c++ stl marshalling

我有一个 C++ 函数可以生成一个有趣的矩形列表。我希望能够从 C++ 库中获取该列表并返回到调用它的 C# 应用程序中。

到目前为止,我正在像这样对矩形进行编码:

struct ImagePatch{ 
   int xmin, xmax, ymin, ymax;
}

然后对一些 vector 进行编码:

void MyFunc(..., std::vector<int>& rectanglePoints){
   std::vector<ImagePatch> patches; //this is filled with rectangles
   for(i = 0; i < patches.size(); i++){
       rectanglePoints.push_back(patches[i].xmin);
       rectanglePoints.push_back(patches[i].xmax);
       rectanglePoints.push_back(patches[i].ymin);
       rectanglePoints.push_back(patches[i].ymax);
   }
}

与 C# 交互的 header 看起来像(并且适用于许多其他功能):

extern "C" {
    __declspec(dllexport) void __cdecl MyFunc(..., std::vector<int>& rectanglePoints);
}

是否有一些关键字或其他我可以做的事情来得到那组矩形?我找到了 this article用于在 C# 中编码对象,但它似乎太复杂而且解释得太少。整数 vector 是执行此操作的正确方法,还是有其他技巧或方法?

最佳答案

STL 是一个特定于 C++ 的库,因此您不能将它作为一个对象直接传递给 C#。

关于 std::vector 的一个保证是 &v[0] 指向第一个元素,并且所有元素在内存中线性排列(换句话说,就内存布局而言,它就像一个 C 数组)

如此编码为 int 数组...这应该不难 - 网络上有很多示例。

已添加

假设您只将数据从 C++ 传递到 C#:

C# 无法处理 C++ vector 对象,所以不要尝试通过引用传递它:相反,您的 C++ 代码必须返回一个指向整数数组的指针...

如果你不打算在多线程中使用这个函数,你可以使用静态存储:

int *getRects(bool bClear)
{
    static vector<int> v; // This variable persists across invocations
    if(bClear)
    {
        v.swap(vector<int>());
    }
    else
    {
        v.clear();
        // Fill v with data as you wish
    }

    return v.size() ? &v[0] : NULL;
}

如果返回的数据很大,调用 getRects(true),释放 v 中的内存。

为简单起见,不要也传递 vector 数据的大小,只需在末尾放置一个标记值(比如 -1),以便 C# 代码可以检测数据的结束位置。

关于c# - 如何将 vector<int> 从 C++ dll 编码到 C# 应用程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2747586/

相关文章:

c# - 是否有可能从 linq 查询中获取左连接列表

c# - 在 HttpClient 和 WebClient 之间做出决定

c# - Encoding.GetString() 仅返回字节数组中的第一个字节

c++ - getNth() 堆栈中的项目

C# - 将月份名称转换为月份编号的最佳方式

c# - 如何在 asp.net C# 中为某些 Controller 操作设置默认路由?

c# - 如何格式化数字以具有相同的位数?

c# - 枚举到字典

C++ 函数按值调用的奇怪行为

c++ - 字符串=“hello”和字符串a =(char * )“hello”在C++中有什么区别?