What is a safe way to pass an array of arrays to a DLL in C#?

匿名 (未验证) 提交于 2019-12-03 08:57:35

问题:

I have an array of arrays that I want to pass into a DLL. I am running into the error "There is no marshaling support for nested arrays."

I can pass a single array in fine but if I stack them up it fails. I need/want a "safe" way of passing in the array of arrays.

private static extern int PrintStuff(string[][] someStringsInGroups, int numberOfGroups, int[] lengthSetsInGroups);

EDIT: I am also willing, with enough discouragement and anguish, to accept a solution involving marshaling.

回答1:

You could convert the double array to a single array (i.e. flatten it). This can be done by keeping width and height variables, and accessing the indices as such:

string atXY = someStringsInSingleArray[(y * width) + x];

The array can then be converted as such:

string * array = new string[width * height];  for (unsigned int y = 0; y < height; ++y) {     for (unsigned int x = 0; x < width; ++x)     {         array[(y * width) + x] = someStringsInGroups[x][y];     } }  // (pass single array to dll)  delete [] array;


回答2:

I just stumbled across what may not be as safe but a lot faster since only the pointers are getting allocated.

http://www.mycsharp.de/wbb2/thread.php?threadid=82380

It is in German, but the code at the end of the page is ready for copy/paste. In my case I just made the class generic to not only support doubles.

Mind you, I do not know about string[][] since I would assume string to be marshalled to char*, so you would have char[][]* rather than double[][] as in the example.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!