我正在使用一个遗留的C库,它可以通过编写用户定义的函数,然后重新编译源代码来扩展。我想避免编译需求,而是使用函数扩展一次(参见下面的伪代码):
此函数将按如下方式实现:
VARIANT_TYPE CallSharedLibFunction(const char* library_name, const char* funcname, const char *params, const char* return_type){
// parse arguments and get data types and count
// initiate variable of data type indicated by return_type, to hold returned variable
/* this is the part I need help with */
// lptr = LoadSharedLibrary(library_name);
// funcptr = GetFunctionAddress(lptr, funcname);
// call function and pass it arguments
retvalue = funcptr(param1, param2, param3);
// wrap up returned value in the VARIANT_TYPE
VARIANT_TYPE ret;
setVariantValue(ret, retvalue, return_type);
return ret;}
注意:尽管名字听起来像“视窗”(VARIANT_TYPE,LoadSharedLibrary和GetFunctionAddress),但我是在Linux (Ubuntu9.10)上开发的。理想情况下,我希望库加载实现是跨平台的(因为我使用的是ANSI C代码)。但如果我必须选择一个平台,那就必须是Linux平台。
如果有人能告诉我如何在任意的共享库中调用函数(理想情况下,以跨平台的方式调用--否则,在Linux上),我将非常感激,这样我就可以实现上面的函数。
发布于 2009-11-10 16:54:29
您可能希望了解一下dlopen、dlsym和类似的函数。它们可以在POSIX (linux、OSX、win32+cygwin等)上工作。
使用dlopen(),您可以打开一个共享库。您的LoadSharedLibrary可以是dlopen()的包装器。GetFuncPtr()函数可以是dlsym()的包装器。你能做的就是围绕dl*()函数编写代码,让它变得健壮,就像做一些错误检查一样。您可能还想在共享库中定义一个接口,即“导出”支持的函数的结构。通过这种方式,您可以获得方法列表,而无需借助读取elf文件。
还有a nice page about function pointers in C and C++。
这里有一个关于用法的快速示例:
void* LoadSharedLibrary(const char* name)
{
   return dlopen(name, RTLD_LOCAL | RTLD_LAZY);
}    
void* GetFunctionAddress(void* h, const char* name)
{
   return dlsym(h, name);
}
const char** GetFunctionList(void* h)
{
   return (char**)dlsym(h, "ExportedFunctions");
}
// Declare a variable to hold the function pointer we are going to retrieve.
// This function returns nothing (first void) and takes no parameters (second void).
// The * means we want a pointer to a function.
void (*doStuff)(void);
// Here we retrieve the function pointer from the dl.
doStuff = GetFunctionAddress(h, "doStuff");
// And this how we call it. It is a convention to call function pointers like this.
// But you can read it as 'take contents of the doStuff var and call that function'.
(*doStuff)();发布于 2009-11-10 16:30:58
对于Linux/POSIX,您可以使用dlopen()系列函数在运行时加载共享库、查找符号地址等。
如果您想添加库依赖项以使处理可加载代码变得更容易(更可移植),请查看glib的module API。
发布于 2009-11-10 17:53:52
使用dlopen/dlsym,并使用-fPIC / FPIC代码编译它
https://stackoverflow.com/questions/1706370
复制相似问题