共享库 (.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 中创建一个 register 函数,以便可执行文件可以为您的 .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屋!