passing 2D array from managed C++ to unmanaged C++
I'm working on a managed C++ wrapper for unmanaged C++ code and have a question. Just for simplicity let's say that I need to pass a 2D array from C# code to Managed C++ to Unmanaged C++. I have no problem with 1D array but stuck with 2D version. Converting it to 1D i开发者_开发技巧s the option, but I want to take a look if there are other ways.
For simplicity let say I want to send 2D array to unmanaged code using intermediate wrapper and change its values.
so here is C# code with a call to managed C++:
MNumeric wrapper = new MNumeric(); //managed C++ object
int[,] dArr = new int[10, 10];
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 10; j++)
{
dArr[i, j] = 10;
}
}
wrapper.ChangeArray(dArr, Convert.ToInt32(Math.Sqrt(dArr.Length)))
Managed C++:
void MNumeric::ChangeArray(cli::array<int,2> ^arr, int mySize)
{
//some code to call Unmanaged C++ passing managed 2D array ???
}
Unmanaged C++
void UNumeric::ChangeArray(int** arr, int mySize)
{
for(int i=0;i<mySize;i++)
{
for(int j=0;j<mySize;j++)
{
arr[i][j]=i;
}
}
}
Thanks a lot for your help.
Looks like I fix one error but got another. My C++ Managed code looks like this now.
void MNumeric::ChangeArray(cli::array<int,2> ^arr, int mySize)
{
pin_ptr<int> p_arr = &arr[0,0];
u_num->ChangeArray((int**)p_arr, mySize);
}
where u_num is just a pointer to UNumeric class. The error I got now is the following:
Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
Any ideas appreciated.
void MNumeric::ChangeArray(cli::array<int,2> ^arr, int mySize) { pin_ptr<int> p = &arr[0,0]; // pin pointer to first element in arr int* np = p; // pointer to the first element in arr UNumeric::ChangeArray((int**)np, mySize); }
You should not use a cast here, it could hide potentially important warnings. Notably, a 2D array is not convertible to an int**
. An int**
, is a pointer to an array of pointers. An int*[]
is a pointer to an array of arrays. You have a function that takes an array of pointers. It wants a managed int[][]
, not an int[,]
. Your compiler would thoroughly have shouted at you for attempting this, if you hadn't casted.
精彩评论