Categories
c gcc linux shared-libraries

How can a shared library (.so) call a function that is implemented in its loading program?

I have a shared library that I implemented and want the .so to call a function that’s implemented in the main program which loads the library.

Let’s say I have main.c (executable) which contains:

void inmain_function(void*);
dlopen("libmy.so");

In the my.c (the code for the libmy.so) I want to call inmain_function:

inmain_function(NULL);

How can the shared library call inmain_function regardless the fact inmain_function is defined in the main program.

Note: I want to call a symbol in main.c from my.c not vice versa which is the common usage.

You’ll need make a register function in your .so so that the executable can give a function pointer to your .so for it’s later use.

Like this:

void in_main_func () {
// this is the function that need to be called from a .so
}
void (*register_function)(void(*)());
void *handle = dlopen("libmylib.so");
register_function = dlsym(handle, "register_function");
register_function(in_main_func);

the register_function needs to store the function pointer in a variable in the .so where the other function in the .so can find it.

Your mylib.c would the need to look something like this:

void (*callback)() = NULL;
void register_function( void (*in_main_func)())
{
callback = in_main_func;
}
void function_needing_callback()
{
callback();
}