在 C++ 类中,我需要调用来自动态加载库的函数。我得到这样的函数指针:
typedef void (*TDef_libfunc)(); // also tried extern "C" typedef void (*TDef_libfunc)();
my_libfunc = (TDef_libfunc)dlsym(thelibrary, "libfunc");
(lib函数已加载,我在调试器中看到它。)
my_libfunc 被声明为成员变量,如下所示:
TDef_libfunc my_libfunc;
从该类的成员函数中,我尝试像这样调用我的函数指针:
my_libfunc();
但是它崩溃了...我这样做对吗?是否可以有一个指向 C 函数的指针的成员变量?
最佳答案
使用 gcc 编译的简单库(如果你编译 g++,则需要添加 extern "C")。
// test-lib.c
// gcc -Wall -g -shared -fpic test-lib.c -o test-lib.so
#include <stdio.h>
void
libfunc()
{
printf("Hello World - Message sent from the libfunc() function.\n");
}
将加载上述库的简单程序(硬编码的路径和函数)。
我有一个段错误,因为我有一个声明的 fn_ 作为指针。
// test-loadlib.cpp
// g++ -Wall -g test-loadlib.cpp -o test-loadlib -ldl
#include <iostream>
#include <dlfcn.h>
typedef void (*TDef_libfunc)(void);
class TestClass
{
public:
TestClass() : lib_(NULL) , fn_(NULL) { }
~TestClass() { if (lib_ != NULL) dlclose(lib_); }
bool
load_library()
{
if ((lib_ = dlopen("./test-lib.so", RTLD_NOW)) == NULL)
return false;
// From man page, this is correct way to store function ptr.
*(void**) (&fn_) = dlsym(lib_, "libfunc");
if (fn_ == NULL)
{
dlclose(lib_);
lib_ = NULL;
return false;
}
return true;
}
void
call_func()
{
if (fn_ != NULL)
(*fn_)();
else
std::cout << "Function not loaded.\n";
}
private:
void* lib_;
TDef_libfunc fn_; // Don't include '*' - it will segfault.
};
int
main(int argc, char *argv[])
{
TestClass tc;
if (tc.load_library())
tc.call_func();
else
std::cout << "Failed to load library.\n";
return 0;
}
我使用存储库中的编译器在 Ubuntu 10.04 下测试并编译了它。
关于c++ - 如何在 C++ 类中拥有指向 C 函数的指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8173304/