Delphi 呼叫 c編寫的動態連結庫,結構體指標作為引數
阿新 • • 發佈:2018-12-30
折騰了一天終於把 結構體指標作為在delphi和c動態連結庫之間函式引數傳遞的問題徹底解決了,花了一天時間的主要原因是沒有領會引數傳遞的精髓。現在把c程式碼和delphi程式碼粘上來,以供後來者學習參考。
delphi程式程式碼:
unit Unit3;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
//定義結構體
type TwoDimArray=Record
x,y:Integer;
end;
function test(a,b:pointer;n1:Integer;var n2:Integer):Integer;stdcall;external 'test.dll' name 'test';
type
TForm3 = class(TForm)
Button1: TButton;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form3: TForm3;
implementation
{$R *.dfm}
procedure TForm3.Button1Click(Sender: TObject);
var
a:Array of TwoDimArray;
b:Array of TwoDimArray;
n1,n2:Integer;
begin
setlength(a,3);
setlength(b,3);
n1:=3;
a[0].x:=11;
a[0].y:=12;
a[1].x:=21;
a[1].y:=22;
a[2].x:=31;
a[2].y:=32;
test(a,b,n1,n2);
ShowMessage(inttostr(b[0].x)+' '+inttostr(b[1].y));
end;
end.
c動態連結庫程式碼(編譯後的庫檔名為test.dll):
typedef struct TwoDimArray{
int x;
int y;
}TwoDimArray;
extern "C" _declspec(dllexport) int test(TwoDimArray *a,TwoDimArray *b,int n1,int *n2)
{
for(int i=0;i<n1;i++){
b[i].x=a[i].x;
b[i].y=a[i].y;
}
*n2=n1;
return 0;
}
需要注意的是delphi中引數前如果加var,那麼在c中對應的引數應該定義為指標,比如:在dephi中引數定義為var n:Integer,則在c中對應的應該定義為int *n
轉自:http://zjw1777.blog.163.com/blog/static/4786512920122210294871/