简体   繁体   中英

passing multidimensional array from C# to C++ DLL

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

If code is open on both ends then have a look on SAFEARRAY data type recommended for Automation.

You can find MSDN reference here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM