如何解决使用dlsym
我有一个C ++程序,我需要打开一个共享库(.so)并从中加载一个C ++类。我已经在Internet上看到了这一点,并且在C和C ++中都使用dlsym()加载了很多东西,所以我知道一切如何工作。但是,我需要做些细微的改变。我使用dlsym()加载的类必须是另一个类的子类,该类在共享对象和主程序使用的标头中定义。这个想法是在运行时加载此类的许多不同的自定义版本。不能在编译时与对象链接。这是我的工作(缩写,但所有重要部分都在这里):
BaseClass.h:
class BaseClass {
public:
virtual ~BaseClass();
virtual int function(int,int);
};
ChildClass.h:
extern "C" BaseClass* makechild();
ChildClass.cpp:
class ChildClass : public BaseClass {
public:
int function(int a,int b) override { return a + b; }
};
BaseClass* makechild() {
return new ChildClass();
}
main.cpp:
std::function<BaseClass*(void)> make;
// note that in the actual program I throw a std::runtime_error with
// dlerror() as its message when this goes wrong,and I don't handle it
make = reinterpret_cast<BaseClass*(*)(void)>(dlsym(handle,"makechild"));
BaseClass* myclass = make();
然后我将ChildClass.cpp编译为ChildClass.so(使用-shared -fpic
),并使用-ldl
以及其他一些与警告相关的标记等对main.cpp进行编译。使用g ++和clang ++,我在运行时遇到两个不同的错误:
- 使用clang ++编译后:
undefined symbol: _ZN9BaseClassD2Ev
- 使用g ++编译后:
undefined symbol: _ZTI9BaseClass
在使用objdump和readelf检查.so文件之后,我确认此符号确实未定义:
...
0000000000000000 *UND* 0000000000000000 _ZN9BaseClassD2Ev
...
0000000000000000 *UND* 0000000000000000 _ZTI9BaseClass
...
我不确定这些符号的确切含义。在阅读了一下ABI文档之后,似乎第一个可能是dtor之类的东西,第二个可能是ctor或类本身的东西。无论如何,我都没有明确尝试加载它们,但是我不确定为什么它们是未定义的。可以使用dlsym()和C ++进行这种多态性/继承设置吗?
编辑:由于有评论,我使用了C ++ filt程序来发现析构函数丢失了(我刚刚添加了virtual ~BaseClass() = default;
来解决此问题)。现在缺少的一件事是_ZTI
,这是该类的typeinfo。
解决方法
事实证明,析构函数和typeinfo是未定义的符号。考虑到我已经做过几次这样的事情,我应该已经看到了,但是没有人能做到完美。无论如何,我为解决此问题所做的就是为= default
添加BaseClass::~BaseClass
和为= 0
添加BaseClass::function
。非常感谢用户G.M.在我对原始帖子提出的评论中!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。