下面的两个代码部分显示了重要信息。真正的工作在第三个代码部分 main.cpp 中完成。
// For all files:
typedef void (*func_ptr)(Event&); // Event is a class with certain methods
foo.cpp
extern "C" void init(std::map<std::string, func_ptr> *func_ptrs)
{
std::cout<<std::endl<<"Initializing..."<<std::endl; // does appear in output, so function does execute
(*func_ptrs)["test"] = stuff; // the stuff function below
}
// this is the function we are trying to add to the func_ptrs map
// It looks like it's added in main.cpp, but calling it in main.cpp seg faults
void stuff(Event &e)
{
std::cout<<"In stuff..."<<std::endl; // seg faults before this line
// do things with e
}
主文件
// Excluding fluff for brevity, use comments to understand location of problem
// In main....
map<string, func_ptr> func_ptrs; // map of strings to func_ptrs
void (*init)(map<string, func_ptr>*);
// some other stuff
handle = dlopen("libfoo.so", RLTD_NOW);
// library opens successfully
*(void **) (&init) = dlsym(handle, "init"); // get the init function from the library
// No, I don't completely understand the above sequence of pointers and reference, but it does open successfully
(*init)(&func_ptrs);
// Executes successfully
// Iterating over func_ptrs shows that the new "test" mapping is in func_ptrs!!
// Next, this should call the stuff function in foo.cpp that was assigned to func_ptrs["test"]
(func_ptrs["test"])(event); // seg fault
所以回顾一下,
- libfoo.so 库正在正确加载
- libfoo.so 中的初始化符号正在被正确检索
- 运行 libfoo 的 init() 后,映射键“test”在 main.cpp 中可见
错误:试图执行 libfoo 的东西,位于 main.cpp 的映射 func_ptrs,seg 错误
注意:另一个选项可能是给 main.cpp 一个“添加到映射”函数,libfoo.so 可以调用它来将映射添加到函数列表中。这看起来更容易/更好吗?
我能够找到很多类似的问题/答案,但没有一个与我正在处理的情况密切相关。非常感谢你们的帮助,我还没有失望。希望我没有搞砸缩短代码。