我需要将一组 C# 字符串传递给 C 代码
示例 C 代码
void print_string_array(const char** str_array, int length){
for (int i = 0; i < length; ++i) {
printf("Sting[%l] = %s\n", i, str_array[i]);
}
}
我尝试过的 C#(这不起作用)
string foo[] = {"testing", "one", "two", "three"};
print_string_array(foo, foo.Length);
[DllImport(my_C_dll, CharSet = CharSet.Ansi)]
private static extern void print_string_array([In][MarshalAs(UnmanagedType.LPArray, ArraySubType=UnmanagedType.LPStr)] string[] sa, int length);
失败并出现 System.AccessViolationException System.AccessViolationException :尝试读取或写入受保护的内存。这通常表明其他内存已损坏。
我也试过(这也没用)
string[] foo = {"testing", "one", "two", "three"};
IntPtr[] s_array = new IntPtr[foo.Length];
for(int i = 0; i < foo.Length; ++i)
{
s_array[i] = Marshal.StringToCoTaskMemAnsi(foo[i])
}
print_string_array( s_array, s_array.Length);
[DllImport(my_C_dll, CharSet = CharSet.Ansi)]
private static extern void print_string_array(IntPtr[] sa, int length);
这也失败了
System.AccessViolationException
System.AccessViolationException : Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
有人知道如何将字符串数组从 c# 传递到 C 吗?
更新:根据 David Heffernan 的建议添加了错误消息。在 C 代码中将 size_t 更改为 int ,因为它不会影响我尝试做的事情。仍然得到相同的错误。