[英]Passing an array of unknown size of structs from c# to c++ dll and back
I asked a similar question yesterday, but this is slightly different. 昨天我问了类似的问题,但这有点不同。 I am having problems passing arrays of struct from c# to c++, and getting this back again. 我在将结构数组从C#传递到C ++时遇到问题,并且再次将其返回。
Here is the c++ code. 这是c ++代码。 Firstly, the struct: 首先,该结构:
struct Tri
{
public:
int v1, v2, v3;
}
and now the c++ dll part: 现在是c ++ dll部分:
extern "C" __declspec(dllexport) void Dll_TriArray(Tri *tri)
{
int num = 10;
tri = new Tri[num];
for (int i = 0; i < num; i++)
{
tri[i].v1 = i + 5;
tri[i].v2 = i + 10;
tri[i].v3 = i + 25;
}
}
and here's the c# code, again starting with the struct: 这是c#代码,同样以struct开头:
[StructLayout(LayoutKind.Sequential)]
public struct Tri
{
public int v1, v2, v3;
}
public class Testing
{
[DllImport("testing.dll")]
static extern void Dll_TriArray(out Tri[] tryArray);
public GetTriArray()
{
Tri[] triArray;
Dll_TriArray(out triArray);
}
}
So the triArray i get when calling the GetTriArray method will come back as null. 因此,我在调用GetTriArray方法时得到的triArray将返回为null。 I have thought about passing an IntPtr in as the argument, but then how does one marshal an intptr into/from an array of struct? 我曾考虑过将IntPtr作为参数传递,但是然后如何将intptr编组到结构数组中/从结构数组中编组呢?
BTW - at this stage, i'm not interested in memory leaks. 顺便说一句-在这个阶段,我对内存泄漏不感兴趣。
I'm not an expert (by any means) in C# but the C++ part gets passed a pointer to Tri-struct, which in C++ can be used like an dynamic array you allocate and fill that correctly but you don't have a way to get it back, because from C-perspective you'd need to modify the caller's (C#) pointer but you only get a copy and not a reference to the original. 我不是C#的专家(无论如何),但是C ++部分传递了一个指向Tri-struct的指针,在C ++中,它可以像动态数组一样使用,您可以正确分配和填充该数组,但是您没有办法找回它,因为从C角度看,您需要修改调用者的(C#)指针,但您只会得到一个副本,而没有对原始对象的引用。
In C++ the closest thing to what you are tying to do, would be to change the prototype to void Dll_TriArray(Tri *&tri)
(call by ref, not call by copy) but I'm not sure how to interface that with C# (probably Dll_TriArray(ref triArray);
). 在C ++中,与您要完成的工作最接近的事情是将原型更改为void Dll_TriArray(Tri *&tri)
(通过引用调用,而不是通过复制调用),但是我不确定如何与C#接口(可能是Dll_TriArray(ref triArray);
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.