Marshal a C char[][] array to C#

亡梦爱人 提交于 2019-12-05 10:26:12

After much searching and hair pulling, this was the solution that worked for me.

Declared the function header in my C# application as:

[DllImport("client.dll", CharSet = CharSet.Ansi)]
public static extern uint queryNumOfServers(ref short numberOfServers, [MarshalAs(UnmanagedType.LPArray)] byte[,] serverNames);

Then called as follows:

byte[,] serverNames = new byte[8,16];
short numServers = -1;
queryNumberOfServers(ref numServers, serverNames);

This returns a double index byte array. From here I used Buffer.BlockCopy() and Encoding.UTF8.GetString() to convert my byte array into a array of strings.

paulsm4

I would use [StructLayout(LayoutKind.Sequential...] and [MarshalAs(UnmanagedType.ByValTStr...].

Here are two good examples:

Marshalling a C 2-Dimensional fixed length char array

Marshaling a C++ two-dimensional fixed length char array as a structure member

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