A r t i c l e s
Navigation

Note: This Wiki is
outdated, personal views
may have changed.
L505 A.I. bot is dead
long live THX 1138

M a i n P a g e

D i r e c t o r y

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
Note: This Wiki is outdated, personal views may have changed.

This wiki contains info on life, health, humans, nature, programming, database, fads, paradigms, poems, principles, theories.

Articles may contain statements which some may find helpful and encouraging, or even discouraging.

Beware, I believe in the Grand Justice system.
_ _ _