我有产生矩形是有趣的名单C ++函数。我希望能够获得该列表出来的C ++库,并返回到C#应用程序正在调用它。
I have a C++ function that produces a list of rectangles that are interesting. I want to be able to get that list out of the C++ library and back into the C# application that is calling it.
到目前为止,我编码的矩形像这样:
So far, I'm encoding the rectangles like so:
struct ImagePatch{
int xmin, xmax, ymin, ymax;
}
和再编码的一些载体:
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#交互的头看起来像(和工程一堆其他功能):
The header for interacting with C# looks like (and works for a bunch of other functions):
extern "C" {
__declspec(dllexport) void __cdecl MyFunc(..., std::vector<int>& rectanglePoints);
}
是否有一些关键字或其他的事情,我可以做的就是这组矩形呢?我发现此文编组在C#中的对象,但似乎这样太复杂,太underexplained。是整数的矢量正确的方式来做到这一点,还是有一些其他的诀窍或方法?
Are there some keywords or other things I can do to get that set of rectangles out? I found this article for marshalling objects in C#, but it seems way too complicated and way too underexplained. Is a vector of integers the right way to do this, or is there some other trick or approach?
STL是一个C ++的特定库,所以你不能直接把它整个作为一个对象为C#。
The STL is a C++ specific library, so you cant directly get it across as one object to C#.
这是保证大约性病的一件事::矢量是&安培; v [0]指向的第一个元素和所有元素位于线性内存中(换言之,其就像在内存方面的C数组布局)
The one thing that is guaranteed about std::vector is that &v[0] points to the first element and all the elements lie linearly in memory (in other words, its just like a C array in terms of memory layout)
所以名帅作为数组为int的......这应该不难 - 有很多在网络上的例子
So marshal as array of int... which shouldn't be hard - There are lot of examples on the web.
添加
假设你只能在C ++中的数据传递到C#:
Assuming you only pass the data from C++ to C# :
C#中不能处理的C ++矢量对象,所以不要尝试通过引用传递的:不是你的C ++ code必须返回一个指向整数数组...
C# cannot handle a C++ vector object, so do not try passing it by reference : Instead your C++ code must return a pointer to an array of ints...
如果您不打算使用多个线程此功能,您可以使用静态存储:
If you are not going to be using this function from multiple threads, you can use static storage :
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(真),如果返回的数据的大小显著,让你释放v内存。
call getRects(true) if the returned data is significant in size, so you release the memory in v.
为了简单起见,而不是传递出的矢量数据的大小也一样,只是把警戒值时结束(如说-1),所以C#code可以检测数据终止的位置。
For simplicity, instead of passing out the size of the vector data too, just put a sentinel value at the end (like say -1) so the C# code can detect where the data ends.