在C#中接收从ANSI C得到的字符串数组,在C#中将它们转换为字符串数组。下面是一个示例代码:
在ANSI C中创建字符串数组并填充它:
char *strings[] = {"Hello", "world", "from", "ANSI", "C"};
在C#中使用Marshal类来编组和解组字符串数组:
using System.Runtime.InteropServices;
[DllImport("ansi_c_dll.dll")]
private static extern IntPtr get_strings();
static void Main(string[] args)
{
IntPtr ptr = get_strings();
int count = 5; // count is the size of the array
string[] strings = new string[count];
IntPtr[] ptrs = new IntPtr[count];
Marshal.Copy(ptr, ptrs, 0, count);
for (int i = 0; i < count; i++)
{
strings[i] = Marshal.PtrToStringAnsi(ptrs[i]);
}
// Now the strings[] array contains the strings from ANSI C
}
在这个示例中,我们首先声明一个名为get_strings()的外部ANSI C函数并使用DllImport来将其导入到C#中。
然后我们使用Marshal类来拷贝指向ANSI C字符串数组的指针到C#中。然后使用循环遍历指向每个字符串的指针,并使用Marshal.PtrToStringAnsi将它们转换为C#中的字符串。
最终,C#中的字符串数组包含ANSI C中的字符串了。