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

前端 未结 4 822
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-30 00:11

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 mai

4条回答
  •  抹茶落季
    2020-11-30 00:35

    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();
    }
    

提交回复
热议问题