从 c# 项目 System.AccessViolationException 调用 c++ char*

calling c++ char* from c# project System.AccessViolationException

我试图从 c# 项目调用 c++ 库方法,但没有成功。我总是得到同样的错误。

System.AccessViolationException: 'Attempted to read or write protected
memory. This is often an indication that other memory is corrupt.'

C++ 方法签名如下所示

int __stdcall getErrorMessage(int errorId, char *&errorMessage);

到目前为止我已经尝试了所有组合,但似乎没有任何效果。

[DllImportAttribute("Lib.dll", EntryPoint = "getErrorMessage", 
CallingConvention = CallingConvention.StdCall)] 
public static extern int getErrorMessage(int errorId, ref StringBuilder errorMessage);

[DllImportAttribute("Lib.dll", EntryPoint = "getErrorMessage",
CallingConvention = CallingConvention.StdCall)] 
public static extern int getErrorMessage(int errorId, ref IntPtr errorMessage);


[DllImportAttribute("Lib.dll", EntryPoint = "getErrorMessage",
CallingConvention = CallingConvention.StdCall)] 
public static extern int getErrorMessage(int errorId, IntPtr errorMessage);

任何帮助将不胜感激。

编辑

我的调用方式如下

var ptr = new IntPtr();

var ret = NativeMethods.getErrorMessage(number, ref ptr);

完成后还有另一个释放内存的调用

获得 IntPtr 后,您应该使用 PtrToStringAuto Or PtrToStringAnsi

将其转换为 string

它终于工作了,当我们尝试使用任意错误代码查询该方法时,就会出现 Hans Passant 提到的问题。

Working code.

var ptr = new IntPtr();

var ret = NativeMethods.getErrorMessage(code, ref ptr);

        if (ptr != IntPtr.Zero)
        {
            message = Marshal.PtrToStringAnsi(ptr);
            NativeMethods.freePointer(ref ptr);
        }

感谢您的帮助。