相关疑难解决方法(0)

使用 p/invoke 将字符串数组从 C# 编组到 C 代码

我需要将 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]);
    }
}
Run Code Online (Sandbox Code Playgroud)

我尝试过的 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);
Run Code Online (Sandbox Code Playgroud)

因 System.AccessViolationException 失败 System.AccessViolationException:尝试读取或写入受保护的内存。这通常表明其他内存已损坏。

我也试过(这也不起作用)

string[] foo = {"testing", "one", "two", "three"};  
IntPtr[] s_array = new IntPtr[foo.Length];

for(int i = 0; i < foo.Length; …
Run Code Online (Sandbox Code Playgroud)

.net c++ pinvoke interop marshalling

2
推荐指数
1
解决办法
7727
查看次数

标签 统计

.net ×1

c++ ×1

interop ×1

marshalling ×1

pinvoke ×1