问题
Having gird my loins and ventured into Legacy Land, having hacked, p-invoked and marshaled every type of wild beast, I now stand before a creature so fierce that, as far as I can tell from an exhausting survey of my brethern-in-arms, not a single code warrior has been left standing.
Here are the details. I am attempting to pass a 2d char array (in c#), inside a structure, to a C dll (no source code), which must be able to make changes to the 2d array.
The C structure:
typedef struct s_beast
{
bool fireBreathing;
char entrails[30][50];
} Beast;
Here is what I have so far in C#, but it is (incorrectly) a 1d array:
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct Beast
{
public BOOL fireBreathing;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 30 )]
public char [] entrails;
}
Who is willing to take a stab at this and, for my sake, the sake of my brethern, and for the sake of future generations, once and for all slay this beast?
回答1:
Interop isn't my strong suite, but C-style multi-dimension arrays are essentially just a syntactic difference on single-dimension arrays.
Something like this may work:
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct Beast
{
public BOOL fireBreathing;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 1500 )] /* 50x30 */
public char [] entrails;
}
public class TamedBeast
{
public Beast WildBeast;
public char[30][50] entrails
{
var 2dEntrails = new char[30][50];
var position = 0;
for (int first = 0; first <30; first++)
{
for (int second = 0; second <50; second++)
{
2dEntrails[first][second] = WildBeast.entrails[position++];
}
}
return 2dEntrails;
}
}
Disclaimer: Untested code from memory, but it should give some ideas. This could cache the 2D array, I didn't just as an initial stab at the beast, plus syncing updates. This can probably be sped up considerably with mem copy operations for each 2nd dimension.
来源:https://stackoverflow.com/questions/11571907/indomitable-beast-a-2d-char-array-inside-a-structure-in-the-belly-of-an-unman