gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 18:37:21 36 4
gpt4 key购买 nike

我有一个 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/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com