折腾了一天终于把 结构体指针作为在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/