20

エクスポートされた C++ DLL から C# プログラムに配列を返す方法がわかりません。グーグルで見つけた唯一のことは、Marshal.Copy() を使用して配列をバッファーにコピーすることでしたが、それでは返そうとしている値が得られず、何を与えているのかわかりません。

これが私が試してきたことです:

エクスポートされた関数:

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

C#部分:

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

    static void Main(string[] args)
    {

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


    }

マネージド/アンマネージドの違いにより、戻り値の型 int[] がおそらく間違っていることはわかっていますが、ここからどこに行くべきかわかりません。整数配列ではなく、文字配列を文字列に返す以外に答えが見つからないようです。

Marshal.Copy で取得している値が返された値ではない理由は、エクスポートされた関数の 'arr' 配列が削除されるためだと考えましたが、誰かがこれをクリアできるかどうかは 100% 確信が持てません。それは素晴らしいことです。

4

1 に答える 1

19

私は、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;
}

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

result値が含まれるようになりました1,2,3,4,5

それが役立つことを願っています。

于 2013-08-04T10:19:01.437 に答える