通多 - 维数组从托管代码到非托管代码 [英] Pass multi - dimensional array from managed code to unmanaged code

查看:133
本文介绍了通多 - 维数组从托管代码到非托管代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要做到以下几点:




  1. 创建这样的C#码连续3 dimesinal数组:



      VAR myArray的=新的短[X,Y,Z]。 
    UnanagedFunction(myarray的);


  2. 将它传递给非托管代码(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:

  1. Create three dimesinal array in c# code like this:

    var myArray = new short[x,y,z];
    UnanagedFunction(myArray);
    

  2. 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆