gna*_*117 2 .net c++ pinvoke interop marshalling
我需要将 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; ++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);
Run Code Online (Sandbox Code Playgroud)
这也失败了
System.AccessViolationException
System.AccessViolationException : Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
Run Code Online (Sandbox Code Playgroud)
有谁知道如何将一组字符串从 c# 传递给 C?
更新:根据 David Heffernan 的建议添加了错误消息。在 C 代码中将 size_t 更改为 int ,因为它不会影响我尝试做的事情。仍然得到相同的错误。
您可以简单地在 C# 中声明您的函数,如下所示:
[DllImport(my_C_dll, CallingConvention=CallingConvention.Cdecl)]
static extern void print_string_array([In] string[] str_array, IntPtr length);
Run Code Online (Sandbox Code Playgroud)
正如所写的那样,您的 C++ 代码似乎使用了cdecl调用约定。因此,您可能需要使 C# 声明匹配。我怀疑这是您面临的主要问题。
另请注意size_t,用于length参数的 , 在 32 位进程中为 32 位宽,在 64 位进程中为 64 位宽。所以正确的 C# 类型是IntPtr. 我个人声明它int同时包含在 C++ 和 C# 代码中。
最后一句忠告。当您遇到失败时,请在问题中包含错误消息。我怀疑您的第一个代码因此错误而失败:
对 PInvoke 函数“MyApp!MyApp.Program::print_string_array”的调用使堆栈不平衡。
如果你把它包括在问题中,那将是一个很大的帮助。
| 归档时间: |
|
| 查看次数: |
7727 次 |
| 最近记录: |