有两种可能性 - 一种需要程序员的预谋。
根据 o/s,有一些与共享库相关的设施,用于从程序或其共享库中查找符号。
在许多 Unix 系统和特别是 Linux 上,这些设施是在<dlfcn.h>
and are dlopen()
and dlsym()
(anddlclose()
等) 中声明的。给定共享库的适当句柄,您可以使用:
int (*ffi_ptr)(const char *) = dlsym(ffi_handle, "ffi_function_name");
您必须考虑强制转换 - 通常是残酷的 - 以避免编译警告。
另一种有预谋的技术是建立一个函数名称和函数指针表,您可以在其中搜索名称并使用相应的指针:
struct ptr_function
{
void (*func_ptr)(void);
const char *func_name;
};
static const struct ptr_function[] =
{
{ func_1, "func_1" },
{ func_2, "func_2" },
{ func_2, "func_synonym" },
};
enum { NUM_PTR_FUNCTION = sizeof(ptr_function) / sizeof(*ptr_function) } ;
Note that this technique allows for synonyms in a way that the dlsym()
mechanism does not. However, the premeditation is often a major stumbling block. It is a technique that harks back to the 80s and early 90s when shared libraries were not universally available. Once again, the need for casts can make the code somewhat more complex.