簡體   English   中英

使用C ++ / CLI包裝器將2D數組從C#傳遞到非托管C ++

[英]passing 2D array from C# to unmanaged C++ using C++/CLI wrapper

我正在一個需要優化的項目中工作,我想將一部分代碼從C#轉換為C ++。 我正在使用C ++ \\ CLI包裝器,但是這種方法對我來說真的很陌生,我還沒有完全理解它。 當我運行程序時,以下代碼返回錯誤,但不知道原因。

C#程序如下:

int[,] Arr = new int[5, 5];

        for (int i = 0; i < 5; i++)
        {
            for (int j = 0; j < 5; j++)
            {
                Arr[i, j] = i + j;
            }
        }

test.MatrixComputation(Arr, Arr.GetLength(0));

C ++ / CLI項目如下:

void MatrixComputation(cli::array<int, 2> ^arr, int size)
    {
        pin_ptr<int> p_arr = &arr[0, 0];
        pu -> ChangeArray((int**)p_arr, size);
    }

非托管C ++代碼:

void Unmanaged::MatrixComputation(int** arr, int size)
{
    for (int i = 0; i < size; i++)
    {
        for (int j = 0; j < size; j++)
        {
            arr[i][j] = i + j;     // line 27
        }
    }

    std::cout << arr[2][2] << std::endl;
}

它編譯良好,但是當我運行它時,出現以下錯誤:

*Line 27: System.NullReferenceException: Object reference not set to an instance of an object*

強制轉換為雙指針是一個壞策略,但這是我唯一想到的事情。 另外,我知道C ++不像C#那樣具有2D數組,但是我需要C#中的多維數組,並且無法更改它以編寫鋸齒狀的數組Arr [] []。

提前致謝。

您應該將托管數組復制到非托管數組,然后進行計算:

void MatrixComputation(cli::array<int, 2> ^arr, int size)
{
    std::unique_ptr<int[]> myArray(new int[size * size]);
    for (auto y = 0; y < size; y++)
    {
        for (auto x = 0; x < size; x++)
        {
            myArray[y * size + x] = arr[x, y];
        }
    }

    pu -> ChangeArray(std::move(myArray), size);
}

void Unmanaged::MatrixComputation(std::unique_ptr<int[]> arr, int size)
{
    for (int i = 0; i < size; i++)
    {
        for (int j = 0; j < size; j++)
        {
            arr[i * size + j] = i + j;
        }
    }

    std::cout << arr[2 * size + 2] << std::endl;
}

暫無
暫無

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

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