【发布时间】:2012-01-26 01:44:33
【问题描述】:
问题很简单,想从托管 C# 代码中读取字符串到我在 WCHAR* [] 中的非托管 C++ 代码。
C函数是:
extern "C" __declspec(dllexport) int __cdecl myfunc(int argc, WCHAR* argv[])
在 C# 中我导入了 DLL:
[DllImport("mydll.dll", CharSet = CharSet.Auto, SetLastError = true, CallingConvention = CallingConvention.Cdecl)]
public static extern int myfunc(int argc, [MarshalAs(UnmanagedType.LPTStr)] StringBuilder str);
我跑了,但是当我尝试读取 C++ 代码中的字符串时,我得到了AccessViolationException : Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
执行此操作的正确方法是什么,反之亦然(即,将字符串从 C++ 非托管代码传递到 C# 托管代码)?
帮助表示赞赏。 谢谢
【问题讨论】:
-
C# 端可能应该使用
StringBuilder。 -
弗拉德是对的。 C 函数需要一个指向 WCHAR 的指针数组。