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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With