将C++数组返回给C#

Dav*_*vid 16 c# c++ arrays dll return

我似乎无法弄清楚如何将数组从导出的C++ DLL返回到我的C#程序.我在google搜索中找到的唯一一件事就是使用Marshal.Copy()将数组复制到缓冲区中,但这并没有给我我想要返回的值,我不知道它给了我什么.

这是我一直在尝试的:

导出功能:

extern "C" __declspec(dllexport) int* Test() 
{
    int arr[] = {1,2,3,4,5};
    return arr;
}
Run Code Online (Sandbox Code Playgroud)

C#部分:

    [DllImport("Dump.dll")]
    public extern static int[] test();

    static void Main(string[] args)
    {

        Console.WriteLine(test()[0]); 
        Console.ReadKey();


    }
Run Code Online (Sandbox Code Playgroud)

我知道返回类型int []可能是错误的,因为托管/非托管差异,我只是不知道从哪里开始.除了将字符数组返回到字符串而不是整数数组之外,我似乎无法找到答案.

我想到我使用Marshal.Copy获得的值不是我返回的值的原因是因为导出函数中的'arr'数组被删除但是我不是100%肯定,如果有人可以清除它那太好了.

Gab*_*iel 15

我已经实施了Sriram提出的解决方案.万一有人想要它在这里.

在C++中,您使用以下代码创建DLL:

extern "C" __declspec(dllexport) int* test() 
{
    int len = 5;
    int * arr=new int[len+1];
    arr[0]=len;
    arr[1]=1;
    arr[2]=2;
    arr[3]=3;
    arr[4]=4;
    arr[5]=5;
        return arr;
}

extern "C" __declspec(dllexport) int ReleaseMemory(int* pArray)
{
    delete[] pArray;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

将调用DLL InteropTestApp.

然后在C#中创建一个控制台应用程序.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.InteropServices;

namespace DLLCall
{
    class Program
    {
        [DllImport("C:\\Devs\\C++\\Projects\\Interop\\InteropTestApp\\Debug\\InteropTestApp.dll")]
        public static extern IntPtr test();

        [DllImport("C:\\Devs\\C++\\Projects\\Interop\\InteropTestApp\\Debug\\InteropTestApp.dll", CallingConvention = CallingConvention.Cdecl)]
        public static extern int ReleaseMemory(IntPtr ptr);

        static void Main(string[] args)
        {
            IntPtr ptr = test();
            int arrayLength = Marshal.ReadInt32(ptr);
            // points to arr[1], which is first value
            IntPtr start = IntPtr.Add(ptr, 4);
            int[] result = new int[arrayLength];
            Marshal.Copy(start, result, 0, arrayLength);

            ReleaseMemory(ptr);

            Console.ReadKey();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

result现在包含值1,2,3,4,5.

希望有所帮助.

  • 好的,那么只要将评论视为对无数谷歌的警示警告,这些警告将在某一天找到你的答案,并且不知道代码会像筛子一样泄漏记忆,并且随意违反访问权限. (4认同)
  • 它没有帮助.你需要展示你如何知道神奇的"5"以及你将如何释放阵列,这样就没有永久性的内存泄漏. (3认同)
  • @Hans,问题是"将C++数组返回到C#".所以,是的,它确实有帮助. (3认同)