通多 - 从托管代码维数组非托管代码
问题描述:
我想做到以下几点:通多 - 从托管代码维数组非托管代码
-
这样C#创建码连续3个dimesinal阵列:
var myArray = new short[x,y,z]; UnanagedFunction(myArray);
-
它传递给非托管代码(C++)像这样:
void UnmanagedFunction(short*** myArray) { short first = myArray[0][0][0]; }
修订 当我尝试下面的代码我有运行时错误:
Attempted to read or write to protected memory.
谢谢!
答
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;
}
这已经过测试,它的工作原理,唯一的限制是,你必须在完成数组指针时调用Marshal.FreeHGlobal
,否则将发生内存泄漏,我还建议您更改C++函数,以便它接受数组维数,否则您将只能使用特定的3d数组大小
+0
非常感谢! ! –
答
我在纯C#中编写它,但如果从Func
中删除unsafe static
,Func
应该在C/C++中工作。要知道,我注意到肯定肯定是OK OK写这个:-) 我使用这个Indexing into arrays of arbitrary rank in C#
static unsafe void Main(string[] args) {
var myArray = new short[5, 10, 20];
short z = 0;
for (int i = 0; i < myArray.GetLength(0); i++) {
for (int j = 0; j < myArray.GetLength(1); j++) {
for (int k = 0; k < myArray.GetLength(2); k++) {
myArray[i, j, k] = z;
z++;
}
}
}
// myArray[1, 2, 3] == 243
fixed (short* ptr = myArray) {
Func(ptr, myArray.GetLength(0), myArray.GetLength(1), myArray.GetLength(2));
}
}
// To convert to C/C++ take away the static unsafe
static unsafe void Func(short* myArray, int size1, int size2, int size3) {
int x = 1, y = 2, z = 3;
int el = myArray[x * size2 * size3 + y * size3 + z]; // el == 243
}
你不能在C++中编写这样的代码。 –
代码的第一部分是在C#第二部分是在C++中,我现在试过编译器允许我的C代码 –
也许你可以改变你的代码为三元组数组。 – Simon