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

前端 未结 4 729
佛祖请我去吃肉
佛祖请我去吃肉 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:45

    The following can be used to load a dynamic library in your code (in case somebody came here after looking at how to do that):

    void* func_handle = dlopen ("my.so", RTLD_LAZY); /* open a handle to your library */
    
    void (*ptr)() = dlsym (func_handle, "my_function"); /* get the address of the function you want to call */
    
    ptr(); /* call it */
    
    dlclose (func_handle); /* close the handle */
    

    Don't forget to put #include and link with the –ldl option.

    You might also want to add some logic that checks if NULL is returned. If it is the case you can call dlerror and it should give you some meaningful messages describing the problem.

    Other posters have however provided more suitable answers for your problem.

提交回复
热议问题