Perl FAQ 3.10: Can I dynamically load C user routines?

Perl FAQ 3.10

Can I dynamically load C user routines?

Yes -- dynamic loading comes with the distribution. That means that you no longer need 18 different versions of fooperl floating around. In fact, all of perl can be stuck into a libperl.so library and then your /usr/local/bin/perl binary reduced to just 50k or so. See DynaLoader(3pm) for details.

In perl4, the answer was kinda. One package has been released that does this, by Roberto Salama*. He writes:

Here is a version of dylperl, dynamic linker for perl. The code here is based on Oliver Sharp's May 1993 article in Dr. Dobbs Journal (Dynamic Linking under Berkeley UNIX).

  dyl.h 
  dyl.c - code extracted from Oliver Sharp's article

  hash.h
  hash.c - Berkeley's hash functions, should use perl's but
	   could not be bothered

dylperl.c - perl usersubs
  user.c - userinit function

sample.c - sample code to be dyl'ed
sample2.c -          "
 test.pl - sample perl script that dyl's sample*.o

The Makefile assumes that uperl.o is in /usr/local/src/perl/... You will probably have to change this to reflect your installation. Other than that, just type 'make'...

The idea behind being able to dynamically link code into perl is that the linked code should become perl functions, i.e. they can be invoked as &foo(...). For this to happen, the incrementally loaded code must use the perl stack, look at sample.c to get a better idea.

The few functions that make up this package are outlined below.


&dyl("file.o"): dynamically link file.o. All functions 
   and non-static variables become visible from within perl. This
   function returns a pointer to an internal hash table corresponding
   to the symbol table of the newly loaded code.

eg: $ht = &dyl("sample.o")


This function can also be called with the -L and -l ld options.


   eg: $ht = &dyl("sample2.o", "-L/usr/lib", "-lm")
       will also pick up the math library if sample.o
       accesses any symbols there.


&dyl_find("func"): find symbol 'func' and return its symbol table entry


&dyl_functions($ht): print the contents of the internal hash table
&dyl_print_symbols($f): prints the contents of the symbol returned by
dyl_find() 

There is very little documentation, maybe something to do for a future release. The files sample.o, and sample2.o contain code to be incrementally loaded, test.pl is the test perl script.

Comments are welcome. I submit this code for public consumption and, basically, am not responsible for it in any way.


Other resources at this site: