共享库(.so)如何调用在其加载程序中实现的函数? [英] How can a shared library (.so) call a function that is implemented in its loading program?
问题描述
我有一个实现的共享库,并且希望.so调用在加载该库的主程序中实现的函数.
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.
假设我有main.c(可执行文件),其中包含:
Let's say I have main.c (executable) which contains:
void inmain_function(void*);
dlopen("libmy.so");
在my.c(libmy.so的代码)中,我想调用inmain_function
:
In the my.c (the code for the libmy.so) I want to call inmain_function
:
inmain_function(NULL);
无论事实是否在主程序中定义了inmain_function
,共享库如何调用inmain_function
.
How can the shared library call inmain_function
regardless the fact inmain_function
is defined in the main program.
注意:我想从my.c中调用main.c中的符号,而不是相反,这是常见用法.
推荐答案
您需要在.so中创建一个注册函数,以便可执行文件可以向.so提供函数指针,以供以后使用.
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.
赞:
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);
register_function需要将函数指针存储在.so中的变量中,.so中的其他函数才能找到它.
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.
您的mylib.c需要看起来像这样:
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屋!