首页 > 编程语言 > 详细

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

时间:2016-06-17 17:09:32      阅读:375      评论:0      收藏:0      [点我收藏+]

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帖子地址

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

原文:http://www.cnblogs.com/Farmer-D/p/5594364.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!