C 呼叫delphi編寫的dll

2022-07-18 04:12:10 字數 2167 閱讀 3552

技術實現

如何逐步實現動態庫的載入,型別的匹配,動態鏈結庫函式匯出的定義,參考下面巨集定義即可:

#define libexport_api extern "c" __declspec(dllexport)

第一步,我先從簡單的呼叫出發,定義了乙個簡單的函式,該函式僅僅實現乙個整數加法求和:

libexport_api int mysum(int a,int b)

c# 匯入定義:

public class refcomm

在c#中呼叫測試:

int isum = refcomm.mysum(,);

執行檢視結果isum為5,呼叫正確。第一步試驗完成,說明在c#中能夠呼叫自定義的動態鏈結庫函式。

第二步,我定義了字串操作的函式(簡單起見,還是採用前面的函式名),返回結果為字串:

libexport_api char *mysum(char *a,char *b)

c# 匯入定義:

public class refcomm

在c#中呼叫測試:

string strdest="";

string strtmp= refcomm.mysum("45", strdest);

執行檢視結果 strtmp 為"45",但是strdest為空。我修改動態鏈結庫實現,返回結果為串b:

libexport_api char *mysum(char *a,char *b)

修改 c# 匯入定義,將串b修改為ref方式:

public class refcomm

在c#中再呼叫測試:

string strdest="";

string strtmp= refcomm.mysum("45", ref strdest);

執行檢視結果 strtmp 和 strdest 均不對,含不可見字元。再修改 c# 匯入定義,將charset從auto修改為ansi:

public class refcomm

在c#中再呼叫測試:

string strdest="";

string strtmp= refcomm. mysum("45", ref strdest);

執行檢視結果 strtmp 為"45",但是串 strdest 沒有賦值。第二步實現函式返回串,但是在函式出口引數中沒能進行輸出。再次修改 c# 匯入定義,將串b修改為引用(ref):

public class refcomm

執行時呼叫失敗,不能繼續執行。

第三步,修改動態鏈結庫實現,將b修改為雙重指標:

libexport_api char *mysum(char *a,char **b)

c#匯入定義:

public class refcomm

在c#中呼叫測試:

string strdest="";

string strtmp= refcomm. mysum("45", ref strdest);

執行檢視結果 strtmp 和 strdest 均為"45",呼叫正確。第三步實現了函式出口引數正確輸出結果。

第四步,修改動態鏈結庫實現,實現整數引數的輸出:

libexport_api int mysum(int a,int b,int *c)

c#匯入的定義:

public class refcomm

在c#中呼叫測試:

int c=0;

int isum= refcomm. mysum(,, ref c);

執行檢視結果isum 和c均為5,呼叫正確。

經過以上幾個步驟的試驗,基本掌握了如何定義動態庫函式以及如何在 c# 定義匯入,有此基礎,很快我實現了變長加密函式在 c# 中的呼叫,至此目標實現。

三、結論

在 c# 中呼叫 c++ 編寫的動態鏈結庫函式,如果需要出口引數輸出,則需要使用指標,對於字串,則需要使用雙重指標,對於 c# 的匯入定義,則需要使用引用(ref)定義。

對於函式返回值,c# 匯入定義和 c++ 動態庫函式宣告定義需要保持一致,否則會出現函式呼叫失敗。定義匯入時,一定注意 charset 和 callingconvention 引數,否則導致呼叫失敗或結果異常。執行時,動態鏈結庫放在 c# 程式的目錄下即可,我這裡是乙個 c# 的動態鏈結庫,兩個動態鏈結庫就在同乙個目錄下執行。

使用Delphi呼叫C 編寫的DLL

1 c 編寫的dll 如下 該dll的功能比較簡單,就是實現乙個整數加法 iaddbase 是乙個抽象類,iadd實現了iaddbase的方法,並採用了單例模式 getaddinstance 為dll對外的介面,返回乙個iadd的物件指標 呼叫者使用該例項就可以呼叫add方法 class iaddb...

Delphi呼叫C 編寫的動態鏈結庫dll的方法

首先宣告這個dll中的函式,然後就可以直接呼叫了 function addnum num1,num2 integer integer stdcall external project1.dll name addnumber function addnum num1,num2 integer inte...

Delphi中高階DLL的編寫和呼叫

根據delphi提供的有關 dll編寫和呼叫的幫助資訊,你可以很快完成一般的 dll編寫和呼叫的 應用程式。本文介紹的主題是如何編寫和呼叫能夠傳遞各種引數 包括物件例項 的 dll。例如,主叫程式傳遞給 dll乙個adoconnection 物件示例作為引數,dll中的函式和過程呼叫通過該物件 例項...