将多维数组从C#传递到C ++ DLL [英] passing multidimensional array from C# to C++ DLL

查看:67
本文介绍了将多维数组从C#传递到C ++ DLL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为将要从C#接口调用的现有C ++ DLL添加功能.该代码在两端都是开放的.

我需要从接口向DLL传递一个简单的固定大小的多维数组.

例如在C#中:

  byte [,,] arrayKeys =新的字节[3,2,4] {{ {0x01, 0x23, 0x45, 0x55}, {0xCD, 0xEF, 0x12} },{{0x9A,0xBC,0xDE,0xAA},{0x78、0x90、0xCD}},{{0x67、0x89、0xA0、0x98},{0x90、0x11、0x22}}}; 

我在线上进行了研究,但还没有真正找到完全适合我的参数的内容.我发现的最多是2D阵列.如果我错过了任何事情,请不要犹豫提供现有链接.

是否有封送处理?我可以直接传递数组吗,或者C ++是否需要某种类型的数组指针?

解决方案

您可以将Array的IntPtr及其尺寸发送给cpp函数.

  byte [,,] arrayKeys =新的字节[3,2,4] {{ {0x01, 0x23, 0x45, 0x55}, {0xCD, 0xEF, 0x12} },{{0x9A,0xBC,0xDE,0xAA},{0x78、0x90、0xCD}},{{0x67、0x89、0xA0、0x98},{0x90、0x11、0x22}}};字节oneDimensionArray =新字节[2 * 3 * 4];对于(int i = 0; i< 2; i ++){对于(int j = 0; j< 3; j ++){对于(int k = 0; k <4; k ++){oneDimensionArray[i*12+j*4+k] = arrayKeys[i,j,k];}}}IntPtr pBytes;pBytes = Marshal.AllocCoTaskMem(2 * 3 * 4/*数组尺寸*/);//将数据复制到分配的内存Marshal.Copy(oneDimensionArray,0,pBytes,i * j * k);//将内存指针发送到C ++函数SendArrayToCPP(pBytes,i,j,k);//释放数组内存Marshal.FreeCoTaskMem(pBytes); 

i'm adding functionality to an existing C++ DLL that will be called from a C# interface. the code is open on both ends.

i need to pass a simple fixed size multidimensional array from the interface to the DLL.

for example in C#:

byte[, ,] arrayKeys = new byte[3, 2, 4] { 
{ {0x01, 0x23, 0x45, 0x55}, {0xCD, 0xEF, 0x12} }, 
{ {0x9A, 0xBC, 0xDE, 0xAA}, {0x78, 0x90, 0xCD} }, 
{ {0x67, 0x89, 0xA0, 0x98}, {0x90, 0x11, 0x22} }};

i've researched online, but haven't really found anything that fits my parameters exactly. most i've found is 2D arrays. if i've missed something, please don't hesitate to provide an existing link.

is there marshaling involved? can i pass the array directly or is there some type of array pointer necessary for the C++?

解决方案

You can send IntPtr of the Array and it's dimensions to cpp function.

byte[, ,] arrayKeys = new byte[3, 2, 4] { 
{ {0x01, 0x23, 0x45, 0x55}, {0xCD, 0xEF, 0x12} }, 
{ {0x9A, 0xBC, 0xDE, 0xAA}, {0x78, 0x90, 0xCD} }, 
{ {0x67, 0x89, 0xA0, 0x98}, {0x90, 0x11, 0x22} }};

byte oneDimensionArray = new byte[2*3*4];
for (int i=0; i<2; i++)
{
   for (int j=0; j<3; j++)
   {
      for (int k=0; k<4; k++)
      {
         oneDimensionArray[i*12+j*4+k] = arrayKeys[i,j,k];
      }
   }
}
IntPtr pBytes;
pBytes = Marshal.AllocCoTaskMem(2*3*4/*array dimensions*/);
//Copy data to allocated memory
Marshal.Copy(oneDimensionArray, 0, pBytes, i*j*k);
//Send memory pointer to C++ function
SendArrayToCPP(pBytes, i, j, k);
//free array memory
Marshal.FreeCoTaskMem(pBytes);

这篇关于将多维数组从C#传递到C ++ DLL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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