通多 - 维数组从托管代码到非托管代码 [英] Pass multi - dimensional array from managed code to unmanaged code
问题描述
我要做到以下几点:
-
创建这样的C#码连续3 dimesinal数组:
VAR myArray的=新的短[X,Y,Z]。
UnanagedFunction(myarray的);
-
将它传递给非托管代码(C ++)是这样的:
无效UnmanagedFunction(短*** myarray的)
{
短的第一= myArray的[0] [0] [0];
}
已更新
当我尝试下面的代码我有运行时错误:
尝试读取或写入受保护的内存。
块引用>
感谢您!
解决方案的IntPtr Array3DToIntPtr(简称[,]瓦尔)
{
IntPtr的RET = Marshal.AllocHGlobal((Val.GetLength(0)+ Val.GetLength( 1)+ Val.GetLength(2))* sizeof的(短));
INT偏移= 0;
的for(int i = 0; I< Val.GetLength(0);我++)
{
为(INT J = 0; J< Val.GetLength( 1); J ++)
{
表示(中间体K = 0; K&下; Val.GetLength(2); K +)
{
Marshal.WriteInt16(保留,胶印,缬氨酸[I,J,K]);
偏差+ = sizeof的(短);
}
}
}
返回RET;
}
这已经过测试,它的作品,唯一的限制是,你必须要叫
Marshal.FreeHGlobal
的数组指针,当你用它做,或者你会得到一个内存泄漏,我也建议你改变你的C ++函数,使其接受数组维度,否则将只能使用特定的尺寸
的三维阵列I would like to do the following:
Create three dimesinal array in c# code like this:
var myArray = new short[x,y,z]; UnanagedFunction(myArray);
Pass it to unmanaged code (c++) like this:
void UnmanagedFunction(short*** myArray) { short first = myArray[0][0][0]; }
UPDATED When I try the following code I have runtime error:
Attempted to read or write to protected memory.
Thank you!!!
解决方案IntPtr Array3DToIntPtr(short[, ,] Val) { IntPtr ret = Marshal.AllocHGlobal((Val.GetLength(0) + Val.GetLength(1) + Val.GetLength(2)) * sizeof(short)); int offset = 0; for (int i = 0; i < Val.GetLength(0); i++) { for (int j = 0; j < Val.GetLength(1); j++) { for (int k = 0; k < Val.GetLength(2); k++) { Marshal.WriteInt16(ret,offset, Val[i, j, k]); offset += sizeof(short); } } } return ret; }
This has been tested and it works, the only limitation is that you have to call
Marshal.FreeHGlobal
on the array pointer when you are done with it or you will get a memory leak, I would also suggest that you change your c++ function so that it accepts the array dimensions or you will only be able to use 3d arrays of specific size这篇关于通多 - 维数组从托管代码到非托管代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!