簡體   English   中英

將C ++數組返回給C#

[英]Return C++ array to C#

我似乎無法弄清楚如何將數組從導出的C ++ DLL返回到我的C#程序。 我在google搜索中找到的唯一一件事就是使用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%肯定,如果有人能清除它那很好啊。

我已經實施了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

希望有所幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM