【问题标题】:Reading string from C# managed code to C++ wchar* [] getting AccessViolation从 C# 托管代码读取字符串到 C++ wchar* [] 获取 AccessViolation
【发布时间】: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 的指针数组。

标签: c# managed wchar


【解决方案1】:

如果您使用的是WCHAR*,或许您应该尝试编组为UnmanagedType.LPWStr,以避免传递预期的一半内存?

Default Marshaling for Strings 上的文档应该为您提供更多详细信息。

【讨论】:

    【解决方案2】:

    我不确定 C# 到 C++,但我可以帮助你解决 C++ 到 C# 的问题。

    从 C++ 代码中导出函数,如下所示:

    DllExport std::string MyFunction( std::string MyParameter) ;
    

    这可以在您的 C# 代码中导入为:

     [DllImport("DLLName.dll", EntryPoint = "MyFunction", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Ansi)]
        [return: MarshalAs(UnmanagedType.LPStr)]
        public static extern string MyFunction([System.Runtime.InteropServices.InAttribute()] [System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.LPStr)] string MyParameter);
    

    现在,在您的 C# 代码中,函数“MyFunction”将接收一个字符串并返回一个字符串。然后就可以调用 MyFunction 进行操作了。

    【讨论】:

      【解决方案3】:

      您的 C 函数似乎需要一个字符串数组,而您传递的是单个字符串。

      我自己没有使用过 P/Invoke,但这个 question 可能会提供一些见解。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-09-05
        • 2010-12-18
        • 2016-06-06
        • 2010-11-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多