将2D数组/矩阵从C ++ dll传递到C#

时间:2018-09-19 12:16:29

标签: c# c++ arrays dll marshalling

我想将2D数组/矩阵从C ++ dll传递到C#程序。 行数是动态的,而列数始终是5。

我首先使用1D数组尝试了此方法,并且有效:

在C ++中:

this

在C#中:

app

当我想对2D数组执行类似操作时,问题就来了。

在C ++中:

extern "C" __declspec(dllexport) int *test()
{
    int Dynamically_changing_rows = rand() & 10 + 5;
    int * oneD_array= new int[Dynamically_changing_rows];
    for (int i =0; i < Dynamically_changing_rows; i++)
    {
        oneD_array[i] = i;
    }

    return oneD_array;
}

在C#中:

[DllImport("myDll.dll"), CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
public static extern IntPtr test();

static void Main()
{
    IntPtr ptr = test();
    int arrayLength = Marshal.ReadInt32(Ptr);
    int[] result = new int[arrayLength];
    Marshal.Copy(ptr, result, 0, arrayLength);
    //Now I have the array in result array. 

    ReleaseMemory(ptr); // function to delete pointer in C++.
}

这为我提供了正确的数组长度(指向第一个值的指针):

extern "C" __declspec(dllexport) int **test()
{
    int **TwoD_array;
    int Dynamically_changing_rows = rand() & 10 + 5;
    TwoD_array = new int*[Dynamically_changing_rows +1];
    int columns = 5;

    // Adding some array values:
    for (int i = 0; i < (Dynamically_changing_rows +1); i++)
    {
        TwoD_array[i] = new int[columns];
        for (int j = 0; j <= columns; j++)
        {
            TwoD_array[i][j] = i*j;
        }
    }
    // Save the number of rows as the first value: 
    TwoD_array[0][0] = Dynamically_changing_rows; 
}

这不起作用:

[DllImport("myDll.dll"), CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
public static extern IntPtr test();

static void main()
{
    intPtr ptr = test();
    IntPtr ptrToPtr = Marshal.ReadIntPtr(ptr);

因为元帅。复制说明说:“ 从一维数组中复制数据。

如何在C#中将2D数组放入 int arrayLength= Marshal.ReadIntPtr(ptrToPtr); 中?

我阅读了关于封送处理数组的documentation,但是我确实对动态变化的数组有所了解。

非常感谢您的帮助!

0 个答案:

没有答案