C 呼叫C 時,字串返回引數出現的訪問異常錯誤

2022-08-29 05:15:10 字數 1061 閱讀 4695

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 呼叫Delphi Dll返回字串的示例

delphi proceduregetsqldata asource pchar adest pchar adestsize integer stdcall var s string begin ifasource nilthenexit s format s 路過!asource move s 1...

c 呼叫有字串引數的 DLL

今天做了乙個動態庫,是需要在c 上面執行的乙個庫。由於一些引數的需要用字串的,但是c 裡面又沒有字串,找了很多資料,才把這個東西弄好。下面介紹一下我的方法。下面是在 c 裡面宣告的 dll 方法。logon lib api long connectlogonsvr handle hhandle,co...

C 字串 引數

1 console.writeline hello 1 輸出的是hello1 console.writeline 1 hello 輸出的是1hello console.writeline 1 2 3 hello 3 2 1 輸出的是6hello321 2 用 定義字串,就可以直接在裡面插入變數 in...