Delphi 开发so库,Delphi 调用SO库

inux桌面系统:Deepin20

一.编写SO库
新建一个项目

项目右键Add Linux Platform

然后项目就变为.so

 添加代码

library mySO;
 
uses
  System.SysUtils,
  System.Classes;
 
{$R *.res}
function testStr: TStringList; cdecl;
var
  str: string;
  strlist: TStringList;
begin
  strlist := TStringList.Create;
  strlist.Add('hello');
  strlist.Add('world');
  result := strlist;
end;
 
function testInt(i: Integer): Integer; cdecl;
begin
  Inc(i);
  result := i;
end;
 
 
exports
  testInt,
  testStr;
 
 
begin
 
end.

编译,生成.so文件

 二.调用SO库
新建项目

 右键Add Linux Platform,然后将so库添加到项目中

添加代码

unit Unit1;
 
interface
 
uses
  System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
  FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs,
  FMX.Controls.Presentation, FMX.StdCtrls,System.IOUtils, FMX.ScrollBox,
  FMX.Memo;
 
type
  TForm1 = class(TForm)
    btn1: TButton;
    btn2: TButton;
    mmo1: TMemo;
    procedure btn1Click(Sender: TObject);
    procedure btn2Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;
 
 
 
var
  Form1: TForm1;
 
  testInt:function (i: Integer): Integer;cdecl;
  testStr:function : TStringList;cdecl;
 
implementation
 
{$R *.fmx}
 
procedure TForm1.btn1Click(Sender: TObject);
var
  Handle1:NativeInt;
  i:integer;
  sl:TStringList;
begin
  mmo1.Lines.Add(TPath.GetLibraryPath+'libmySO.so');
 
  Handle1:=LoadLibrary(PWideChar('libmySO.so'));
  mmo1.Lines.Add(IntToStr(Handle1));
  if Handle1<>0 then
  begin
    @testInt:=GetProcAddress(Handle1,'testInt');
    @testStr:=GetProcAddress(Handle1,'testStr');
 
    if Assigned(testInt) then
    begin
      i:=testInt(1000);
      mmo1.Lines.Add(IntToStr(i));
    end
    else
    begin
      mmo1.Lines.Add('nil');
    end;
 
    sl:=testStr;
    mmo1.Lines.AddStrings(sl);
 
    FreeLibrary(Handle1);
  end;
end;
 
procedure TForm1.btn2Click(Sender: TObject);
begin
  Application.Terminate;
end;
 
end.
 F9 运行,结果如下

源码下载https://download.csdn.net/download/zhanglu_king/20464265
————————————————
版权声明:本文为CSDN博主「小米很好吃」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/zhanglu_king/article/details/119085973

你可能感兴趣的:(Delphi,so,调用,动态链接库,fmx)