Return C++ array to C#

前端 未结 1 436
不思量自难忘°
不思量自难忘° 2020-12-13 10:48

I can\'t seem to figure out how to return an array from an exported C++ DLL to my C# program. The only thing I\'ve found from googling was using Marshal.Copy() to copy the a

相关标签:
1条回答
  • 2020-12-13 10:52

    I have implemented the solution Sriram has proposed. In case someone wants it here it is.

    In C++ you create a DLL with this code:

    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;
    }
    

    The DLL will be called InteropTestApp.

    Then you create a console application in 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();
            }
        }
    }
    

    result now contains the values 1,2,3,4,5.

    Hope that helps.

    0 讨论(0)
提交回复
热议问题