How to call an unknown function from a dynamic library?

I need to realize the ability to call a function from .so without any knowledge of the function at compile time. I will only receive this information at runtime. How can i do this?

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

At the time of compilation, the function signature is not known.

OS is Linux on raspberry PI.

+6
source share
2 answers

dlopen and dlsym (or their Windows equivalents) allow you to load a โ€œshared objectโ€ (a compiled code module) whose file name is determined at run time, and then retrieve function pointers for routines whose names are also determined at run time. 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 type of function pointer and then name it.

If you do not know the number and type of arguments that must pass before execution, then dlopen and dlsym not enough, and in fact this is one of the things that still requires a modest number of hands - written assembly language. In C or C ++, it is simply impossible to use even regular compiler extensions to synthesize a call whose argument list is determined at run time. (GCC has extensions that sound like they are for this, but they are not common enough to be useful, except in the depths of their own GCC runtime libraries.)

Fortunately, someone has already written assembly language for you and wrapped it in a beautiful library: libffi . It is reliable, licensed, and supports every processor that you probably care about, and more. On x86, it also conveniently smooths out some of the differences between Unix and Windows.

+11
source

It looks like you need a late linux binding .

You can load your dlopen shared library and then use dlsym to get your function (assuming you know the name of the function).

After that, you will need to use your signature information to correctly call this function (at compile time you usually point this pointer to the appropriate type).

Please note: this is NOT portable across different operating systems.

+6
source

Source: https://habr.com/ru/post/971974/


All Articles