Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call unknown function from dynamic library?

I need to implement an ability of calling a function from .so without any knowledge of the function at compile time. I'll have that information provided only on runtime. How can I do that?

We can assume that the function I want to call is exported from the library, there is nothing that needs to be done on the library side.

Function signature is not known on compile time.

OS is Linux on Raspberry PI.

like image 875
Adam Kłobukowski Avatar asked Jul 09 '14 13:07

Adam Kłobukowski


1 Answers

dlopen and dlsym (or their Windows equivalents) allow you to load a "shared object" (module of compiled code) whose filename is determined at runtime, and then retrieve function pointers for subroutines whose names are also determined at runtime. However, the type signature of each such function -- the number and type of arguments to pass -- must still be known at compile time, so that you can convert the void * returned by dlsym to the correct function-pointer type and then call it.

If you don't know the number and type of arguments to pass until runtime, then dlopen and dlsym are not enough, and in fact, this is one of the things that still requires a modest amount of hand-written assembly language. There is simply no way within C or C++, even with common compiler extensions, to synthesize a call whose argument list is determined at runtime. (GCC has extensions that sound like they are for this, but they are not general enough to be useful except deep in the guts of GCC's own runtime libraries.)

Fortunately, someone has already written the assembly language for you and wrapped it up in a nice library: libffi. It's reliable, permissively licensed, and supports every CPU you are likely to care about and more besides. On x86 it also conveniently smooths over some of the differences between Unix and Windows.

like image 120
zwol Avatar answered Sep 23 '22 09:09

zwol