[英]Is it possible to pass struct list from c++ to C#
我有兴趣从我的C ++代码中调用一段.NET代码。 .NET代码是用' generate COM visible '编译的独立dll,它包含一个接受'item'结构列表的方法。
像这样的东西:
struct item {
int a;
int b;
}
[ComVisible(true)]
[ClassInterface(ClassInterfaceType.None)]
public interface Ifoo {
int GetFoo(ref IntPtr items,int nItems);
}
public class foo : Ifoo {
int GetFoo(ref IntPtr items,int nItems)
{
for (int ix = 0; ix < numMatches; ix++)
{
it = (item)Marshal.PtrToStructure((IntPtr)((long)items + Marshal.SizeOf(typeof(item))*ix)),typeof(item));
}
}
}
在c ++部分,我有类似的东西..
std::vector<struct> foo;
foo.push_back(stru1); // stru1 is initialized anywhere...
foo.push_back(stru2); // and so on...
netInstance->GetFoo(reinterpret_cast<long*>(foo.data()),foo.size());
但这不起作用..我得到的只是内存异常..
我也尝试过其他方法,比如SAFEARRAY,但它似乎不适用于自定义结构。
谢谢!
在Windows上,long可能是32位整数。 您可以尝试在C ++代码中将long*
更改为long long*
,以便数组的大小与数据的大小相匹配。
你是否控制C#部分和C ++部分? 而不是封送数组,更改界面以使用单个项目。 调试会更容易。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.