C#调用C++时,字符串返回参数出现的访问异常错误

C++函数原型:

BOOL _stdcall PSStartup(HANDLE hPrintps, LPCSTR lpszDatabasePath, LPCSTR lpszSpoolFile);

lpszSpoolFile为返回参数,由PSStartup中赋值并带回来。

一开始我在C#中的声明是:

[DllImport("PrintScu.dll", CallingConvention = CallingConvention.StdCall)]
public extern static int PSStartup(IntPtr hPrintps, string lpszDatabasePath, ref string lpszSpoolFile);

但是在实际调用的时候出现错误:

System.AccessViolationException was unhandled
  Message=Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
  Source=mscorlib
  StackTrace:
       at System.String..ctor(SByte* value)
       at System.StubHelpers.CSTRMarshaler.ConvertToManaged(IntPtr cstr)

 

网上找了一圈之后发现这样声明不行,不能使用ref string,而需要使用StringBuilder,于是改成以下声明,测试通过:

[DllImport("PrintScu.dll", CallingConvention = CallingConvention.StdCall)]
public extern static int PSStartup(IntPtr hPrintps, string lpszDatabasePath, StringBuilder lpszSpoolFile);

stackoverflow帖子地址

posted @ 2016-06-17 16:14  Farmer.D  阅读(1065)  评论(0)    收藏  举报