Forum > Beginners

how to use shared library in linux

(1/2) > >>

ciammaruca:
please, if possible, a working example for a simple example, for linux.
I have this classic example:
http://tldp.org/HOWTO/Program-Library-HOWTO/more-examples.html#AEN280
but this wiki is not clear for me:
http://wiki.freepascal.org/Lazarus/FPC_Libraries#Loadlibrary_-_dynamically_loading_a_dynamic_library

So, how to call hello function in libhello.so.0.0?
Please, if possible, a complete and working example, not teorically speaking, but for freepascal really beginners .
The only starting point is the  libhello.so.0.0 already made.
thanks

Fred vS:
Hello.

Here how to dynamically load the library.


--- Code: ---uses
...,
 DynLibs.pas,...
...
 var
mylib_handle :TLibHandle=dynlibs.NilHandle;
--- End code ---

and , when you need your lib (could be at Form.OnCreate)


--- Code: ---mylib_handle := LoadLibrary('mylib.so');

// according the lib is in executable folder, otherwise write the full path.

--- End code ---

When you close your app (or if you do not need the lib)


--- Code: ---UnloadLibrary(mylib_handle);
--- End code ---


Fred vS:
... And for the hello function... =>


--- Code: ---
uses
...,
 DynLibs.pas,...
...
var
hello: function():String ; cdecl;
...
implementation
...
Pointer(hello):=DynLibs.GetProcedureAddress(mylib_handle,PChar('hello'));
...

--- End code ---

And when you want to call hello function =>


--- Code: ---...
 mystring := hello;
...

--- End code ---

ciammaruca:
ok,
so, i have this libhello.c compiled in libhello.so.0.0:
#include <stdio.h>
int hello(int a,int b) {
a=a+b;
return a;
}

and this is freepascal:
var
  Form1: TForm1;
  mylib_handle :TLibHandle=dynlibs.NilHandle;
  FuncResult:integer;
implementation

{$R *.lfm}

{ TForm1 }

procedure TForm1.FormCreate(Sender: TObject);
begin
 Mylib_handle := LoadLibrary('/home/rob/Copy/linux/programmazione-C/libreria/libhello.so.0.0');
 FuncResult:=hello(3,5);
 form1.edit1.text:=inttostr(FuncResult);

end.               

but: Error: Identifier not found "hello"

Fred vS:
Hello


--- Code: ---var
  Form1: TForm1;
  mylib_handle :TLibHandle=dynlibs.NilHandle;
  hello: function(a : integer; b : integer):integer ; cdecl;

implementation
...
procedure TForm1.FormActivate(Sender: TObject);
begin
 mylib_handle := LoadLibrary('/home/rob/Copy/linux/programmazione-C/libreria/libhello.so.0.0');
Pointer(hello):=DynLibs.GetProcedureAddress(mylib_handle,PChar('hello'));
 edit1.text:=inttostr(hello(3,5));
end;
...
end.               
--- End code ---

Navigation

[0] Message Index

[#] Next page

Go to full version