[英]How to have a pointer to a C function inside a C++ class?
In a C++ class, I need to call functions that come from a dynamically loaded library. 在C ++类中,我需要调用来自动态加载的库的函数。 I get the function pointers like this: 我得到这样的函数指针:
typedef void (*TDef_libfunc)(); // also tried extern "C" typedef void (*TDef_libfunc)();
my_libfunc = (TDef_libfunc)dlsym(thelibrary, "libfunc");
(The lib function is loaded, I see it in the debugger.) (lib函数已加载,我在调试器中看到它。)
my_libfunc is declared as a member variable like this: my_libfunc声明为成员变量,如下所示:
TDef_libfunc my_libfunc;
From within a member function of that class, I try to call my function pointer like this: 在该类的成员函数中,我尝试这样调用函数指针:
my_libfunc();
But it crashes... Am I doing this right? 但是它崩溃了...我在这样做吗? Is it possible to have a member variable that is a pointer to a C function? 是否可以有一个成员变量,它是一个指向C函数的指针?
Simple library compiled using gcc (if you compile will g++ you will need to add extern "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");
}
Simple program that will load the above library (path and function hard-coded). 将加载上述库的简单程序(路径和函数经过硬编码)。
I had a seg fault because I had an declared fn_ as a pointer. 我有段错误,因为我有一个声明的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;
}
I tested and compiled this under Ubuntu 10.04 using the compiler from the repository. 我使用存储库中的编译器在Ubuntu 10.04下对其进行了测试和编译。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.