且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将多维数组从C#传递到C ++ DLL

更新时间:2023-01-16 19:58:56

您可以将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  

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);