簡體   English   中英

Delphi7中使用的C ++ DLL函數

[英]C++ DLL function used in Delphi7

我想在我的delphi 7項目中使用c ++ DLL。我在我的delphi7項目中成功調用了DLL的一個函數,但在另一個參數是stringbuilder的函數中得到錯誤。 C ++函數詳細信息如下。(我從dll的頭文件中獲取)

WN_COMM_ERR WINAPI MYFUNCTION(WN_COMM_HANDLE handle, const char *command, char *answer, unsigned long maxlen, unsigned long timeout_ms, WN_ANSWER_TYPE *type);

答案類型是枚舉類型: -

 typedef enum {
    WN_ANSWER_ACK = '>',        // An OK frame was received
    WN_ANSWER_NACK = '!',       // An ERR frame was received
    WN_ANSWER_TOUT = 0,         // Command timed out before an answer could be received
}WN_ANSWER_TYPE;

我已經在c#代碼中成功調用了相同的函數並且它正在工作。但是我不知道如何在delphi7上調用它,因為answer參數是stringbuilder類型而在delphi7中它們不是任何stringbuilder類型的東西。 我曾嘗試使用Pansichar,string,pchar,但沒有在answer類型變量中獲取值: -

C#聲明:工作

    [DllImport("wn_comm.dll", CharSet = CharSet.Unicode)]
    public static extern UInt32 MYFUNCTION(IntPtr handle, string command, StringBuilder answer, UInt32 maxlen, UInt32 timeout_ms, ref Int32 answer_type);

調用C#函數:工作

WriteNowWrapper.MYFUNCTION(this.comm_handle, command, sbAnswer, (uint)sbAnswer.Capacity, Timeout, ref answerType)

當我從我的c#應用程序上面調用時,我已成功接收answertype和sbanswer變量值。

Delphi7聲明:不工作

function MYFUNCTION  (handle:Longint; command:string;var answer:PAnsichar; maxlen:integer; Timeout:integer; VAR answretype:INTEGER) : longint; stdcall; external 'wn_comm.dll';

Delphi7調用函數:不工作

   MYFUNCTION(self.comm_Handle,command,answer,2,Timeout,answerType)

當我從delphi7應用程序調用MYFUNCTION時。 它成功執行並更新answertype中的值,這是整數類型參數但在回答變量中我變得空白。

任何人都可以幫助我,我做錯了什么?

您的Delphi函數聲明不正確。 您不能使用本機Delphi類型的string 答案參數不是var參數。

聲明應該是:

function MYFUNCTION(
    handle: Integer; 
    command: PAnsichar;
    answer: PAnsichar; 
    maxlen: Cardinal; 
    timeout_ms: Cardinal; 
    out answer_type: Integer
): Cardinal; stdcall; external 'wn_comm.dll';

您問題中缺少的細節是分配answer的部分。 你明確地在C#代碼中這樣做。 這看起來像這樣:

StringBuilder sbAnswer = new StringBuilder(256);

我已經猜到了用於容量的價值。 在您的Delphi調用代碼中,您需要類似的東西。

var
  handle: Integer; 
  command: AnsiString;
  answer: AnsiString;    
  timeout_ms: Integer; 
  answer_type: Integer;
  err: Integer;
....
handle := ...;
command := ...;
SetLength(answer, 256);
timeout_ms := ...;
err := MYFUNCTION(
    handle, 
    PAnsiChar(command), 
    PAnsiChar(answer), 
    Length(answer),
    timeout_ms,
    answer_type
);

鍵入無法訪問DLL,可以說出了什么問題。 但試試這個開始吧

function WN_ExeCommandA  (handle:Longint; command: PAnsichar;var answer:PAnsichar; maxlen:integer; Timeout:integer; VAR answretype:INTEGER) : longint; stdcall; external 'wn_comm.dll';

如果我能看到WN_ANSWER_TYPE的c ++定義,我可以幫助你更多。

暫無
暫無

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

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