[fpc-devel] Dynamically Loading Libraries

Sergei Gorelkin sergei_gorelkin at mail.ru
Mon Nov 2 21:45:25 CET 2009

Vincent Snijders wrote:

>> Should do the following right? Correct me if i'm wrong:
>> Static function:
>> function foobar_dosomething(a:cint; b:cdouble): cint; extdecl;external 
>> foobarlib;
>> Becomes a dyn function:
>> var foobar_dosomething: function(a:cint; b:cdouble): cint; extdecl;
> And a statement to initialize the variable.
I'd also note that the current approach (loading all functions at once) actually defeats the nature 
of dynamic linking, and smartlinking as well. If some function is absent in the library, error will 
occur on loading regardless of whether this function is actually used by the program. With static 
linking, if the problematic function isn't used, there will be no loading error.
For this reason, I use the following approach in my projects (in pseudocode):


function foo(args): integer;


   tfoo = function(args): integer;

   bad_ptr = pointer(1);

   _foo: pointer = bad_ptr;

function foo(args): integer;
   p: PPointer;
   p := @_foo;
   Result := E_NOTIMPL;         // other values may be used, or an exception raised
   if p^ = bad_ptr then
     p^ := GetProcAddress(libHandle, 'foo_name');
   if Assigned(P^) then
     Result := tfoo(p^)(args);

Such approach, of course, introduces somewhat bigger overhead, but allows the compiler to optimize 
unused parts away.


More information about the fpc-devel mailing list