【问题标题】:Marshal C++ int array to C#将 C++ int 数组编组为 C#
【发布时间】:2011-04-16 03:28:01
【问题描述】:

我想将一个整数数组从 C++ 编组到 C#。我有一个非托管 C++ dll,其中包含:

DLL_EXPORT int* fnwrapper_intarr()
{
    int* test = new int[3];

    test[0] = 1;
    test[1] = 2;
    test[2] = 3;

    return test;
}

在标头 extern "C" DLL_EXPORT int* fnwrapper_intarr(); 中声明

然后我使用 pinvoke 将其编组为 C#:

[DllImport("wrapper_demo_d.dll")]
[return: MarshalAs(UnmanagedType.SafeArray)]
public static extern int[] fnwrapper_intarr();

我使用这样的功能:

int[] test = fnwrapper_intarr();

但是,在程序执行期间,我收到以下错误:SafeArray cannot be marshaled to this array type because it has either nonzero lower bounds or more than one dimension.

我应该使用什么数组类型?或者有没有更好的方法来编组数组或整数向量?

【问题讨论】:

  • 如果你是 fnwrapper_intarr 的作者,有什么反对返回一个安全数组(或更好作为参数)的吗?

标签: c# c++


【解决方案1】:
[DllImport("wrapper_demo_d.dll")] 公共静态外部 IntPtr fnwrapper_intarr(); IntPtr ptr = fnwrapper_intarr(); int[] 结果 = 新的 int[3]; Marshal.Copy(ptr, result, 0, 3);

您还需要在非托管 Dll 中编写 Release 函数,该函数删除由 fnwrapper_intarr 创建的指针。该函数必须接受 IntPtr 作为参数。

DLL_EXPORT 无效 fnwrapper_release(int* pArray) { 删除[] pArray; } [DllImport("wrapper_demo_d.dll")] 公共静态外部无效 fnwrapper_release(IntPtr ptr); IntPtr ptr = fnwrapper_intarr(); ... fnwrapper_release(ptr);

【讨论】:

  • +1 太好了!它有效,但我认为它应该是 Marshal.Copy 而不是 Marshal::Copy
  • 如果不知道C#端的数组大小怎么办?
猜你喜欢
  • 1970-01-01
  • 2012-06-21
  • 2014-03-02
  • 2011-09-13
  • 2014-05-18
  • 2016-04-13
  • 2019-12-04
  • 2021-08-20
相关资源
最近更新 更多