A r t i c l e s
|
Export Function From Elf
|
Tested on linux. Exports function from ELF (executable) and has the dynamic shared object (dynamic link library) call this function from the elf.
THE PROGRAM:
program prog;
{$mode objfpc}
uses
dynlibs;
// static linking.. optional..
//function dllf: longint; external 'dyn';
// this function is exported from the EXE
function exetest: longint;
begin
writeln('exe test');
end;
exports
exetest;
const
{$ifdef unix}
libname = './libdyn.so';
{$endif}
{$ifdef win32}
libname = '.\dyn.dll';
{$endif}
var
dllf: function: longint;
lh: tlibhandle;
begin
// dynamic linking..
lh:= loadlibrary(libname); // load dyn.so (unix) or dyn.dll (ms windows)
if lh = nilhandle then begin writeln('dyn library returned nil handle'); halt; end;
pointer(dllf):= getprocaddress(lh, 'dllf'); // get function from dll
// call function in dll, which calls function in exe, and then prints
// a result number 5
writeln(dllf);
writeln('end of program');
end.
THE LIBRARY:
library dyn;
{$mode objfpc}
{$ifdef win32}
const
progname = '.\prog.exe';
{$endif}
{$ifdef win32}
function exetest: longint; external progname;
{$endif}
{$ifdef unix}
function exetest: longint; external name 'exetest';
{$endif}
function dllf: longint;
begin
exetest;
result:= 5;
end;
exports dllf;
begin
end.
Notes:
- on linux, missing 'external name' will cause it not to work! On Windows you can use external 'prog.exe' but you don't need external name 'functionname'.
- in fpc 2.0.4 (and possibly later versions, and earlier versions) smartlinking a library on linux is not recommended. Why? because I found that smartlinking caused the library to skip out finalization of units in the uses clause! When smartlinking was turned off, finalization of all units worked fine.
- in fpc 2.0.4 (and possibly later versions, and earlier versions) BSD (freebsd, netbsd, openbsd) probably won't work. Why? because I found that bsd has some basic errors that need to be resolved first. See this bug report
- in fpc 2.0.4 (and possibly later versions, and earlier versions) exporting functions from an executable on linux will cause initialization and finalization not to occur in library units, no matter whether smartlinking is on or off. See this bug report
|
|
About
This site is about programming and other things.
|