簡體   English   中英

在Delphi中實現C DLL

[英]Implementing a C DLL in Delphi

我正在努力從C dll實現一個函數。 它被宣布為

int DetectTransactionCode(wchar_t* wi_type, wchar_t* wi_id);

如果已經在我的delphi代碼中聲明並調用了它

function DetectTransactionCode (var wi_type, wi_id: PWideChar): Integer;
     cdecl; external 'WiGroupDetect.dll';

procedure TForm20.Button2Click(Sender: TObject);
var witype,wi_id : widestring;
res : integer;
begin
 res := DetectTransactionCode(PWideChar(witype),PWideChar(wi_id));
 showmessage(res.tostring);
 ShowMessage(witype +' & ' +wi_id);
end;

我收到了結果,但是我的witype和wi_id導致訪問違規。

我也嘗試過:

Function  DetectTransactionCode (var witype,wi_id :widestring ) : Integer cdecl;
                  external 'WiGroupDetect.dll';

procedure TForm20.Button2Click(Sender: TObject);
var witype,wi_id : widestring;
 res : integer;
begin
 res := DetectTransactionCode(witype,wi_id);
 showmessage(res.tostring);
 ShowMessage(witype +' & ' +wi_id);
end;

我假設兩個參數都是參數。 第三方提供以下內容:

成功返回1,取消/失敗返回0

注意:阻止調用僅在以下情況下返回:1 - 檢測到wiCode,2 - 調用KillDetectionProcess(),3 - 發生某些錯誤或故障,或4 - 最終超時(30分鍾)到期。

參數:wi_type成功返回檢索到的令牌類型(即QR的“WIQR”); 取消/失敗時“無”或“無”。 wi_id返回成功檢測到的wiCode; 取消時取消“取消”; 或者有關失敗的其他錯誤信息(即“錯誤:......”)。

我已經嘗試將參數更改為ansistring,unicodestring但仍然遇到同樣的問題。 我懷疑它與var參數有關,但不確定如何克服它。 任何援助將不勝感激。

我得到了他們的C樣本實現

[DllImport("WiGroupDetect.dll", EntryPoint = "DetectTransactionCode", CallingConvention =             CallingConvention.StdCall, CharSet = CharSet.Unicode)]
private static extern int DetectTransactionCode([MarshalAsAttribute(UnmanagedType.LPWStr)]  StringBuilder strWITYPE, [MarshalAsAttribute(UnmanagedType.LPWStr)] StringBuilder strUID);

不確定這是否會改變我的Delphi實現

這兩個參數的類型為wchar_t* ,它是指向16位字符的指針。 通常,這意味着指向以UTF-16寬字符結尾的空終止數組的指針。

因此,所呈現的代碼的正確翻譯是:

function DetectTransactionCode (wi_type, wi_id: PWideChar): Integer;
    cdecl; external 'WiGroupDetect.dll';

您使用了WideString類型的var參數。 這將匹配指向BSTR參數,這是非常不同的。

我假設cdecl調用約定,我遇到的每個C編譯器的默認值。 如果你有一些額外的信息表明函數是stdcall ,那就這樣吧。 但正如問題所寫,這是cdecl

目前尚不清楚數據是如何流動的。 兩個字符串參數是輸入還是輸出? 是一個在另一個嗎? 如果要么輸出參數,那么您需要一些方法來了解要分配的緩沖區大小。 函數不允許您傳遞緩沖區長度的事實表明數據流入。也就是說,在這種情況下,參數應該是C代碼中的const wchar_t* 這里有很多不確定因素。 請注意,函數原型並未完全定義函數的語義。

感謝大衛幫助他們的答案。 我設法使用此代碼。 我知道如果傳回的字符串比我提供的字符串長,那么就會出錯

function DetectTransactionCode (wi_type, wi_id: pwidechar): Integer;
stdcall; external 'WiGroupDetect.dll';

procedure TForm20.Button2Click(Sender: TObject);
var witype,wi_id :  widestring;
 res : integer;
begin
 setlength(witype,10);
 setlength(wi_id,100);
 res := DetectTransactionCode(pwidechar(witype),pwidechar(wi_id));
 showmessage(res.tostring);
 setlength(witype,pos(#0,witype)-1);
 setlength(wi_id,pos(#0,wi_id)-1);
 ShowMessage(trim(witype) +' & ' +trim(wi_id));
end;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM