共享库(.so)如何调用在其加载程序中实现的函数? [英] How can a shared library (.so) call a function that is implemented in its loader program?
问题描述
我有一个我实现的共享库,我希望.so在加载库的主程序中调用一个函数。
假设我有main .c(可执行文件)包含:
void inmain_function(void *);
dlopen(libmy.so);
在my.c(libmy.so的代码)中,我想调用 inmain_function
:
inmain_function(NULL);
共享库如何调用 inmain_function
在主程序中定义 inmain_function
这一事实。
注意:我想从my.c中调用main.c中的一个符号,反之亦然,这是常见的用法。
您需要在.so中创建一个注册函数,以便可执行文件可以为函数指针指向.so,使用。
像这样:
void in_main_func(){
//这个函数需要从.so
中调用
void(* register_function)(void(*)());
void * handle = dlopen(libmylib.so);
register_function = dlsym(句柄,register_function);
register_function(in_main_func);
register_function需要将函数指针存储在.so中的变量中,其中的另一个函数。
你的mylib.c需要看起来像这样:
void(* callback)()= NULL;
void register_function(void(* in_main_func)())
{
callback = in_main_func();
void function_needing_callback()
{
callback();
}
I have a shared library that I implement and I want the .so to call a function in the main program that 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();
}
这篇关于共享库(.so)如何调用在其加载程序中实现的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!