是否可以将结构列表从C 传递到C#

Is it possible to pass struct list from c++ to C#

本文关键字:列表 结构 是否      更新时间:2023-10-16

我有兴趣从我的C 代码调用.NET代码。.NET代码分为" 生成com可见"的分离的dll,它由接受"项目" struct的列表的方法组成。

类似的东西:

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,但似乎与自定义结构不起作用。

谢谢!

在窗口上,长长可能是32位整数。您可以尝试在C 代码中将long*更改为long long*,以使数组的大小匹配数据的大小。

您是否控制C#部分和C 部分?而不是元帅阵列,而是将界面更改为与单个项目一起使用。调试将更容易。