In a C++ code I'm trying to have a main module that defines a polymorphic base class, which dynamically loads derived classes for it at runtime. The main module has something like:
class Base {
public:
virtual ~Base();
virtual int f() = 0;
};
int main() {
auto make_a_ptr = /* load function pointer make_a from module using dsym */;
Base* a = make_a_ptr();
std::cout << a->f() << std::endl;
delete a;
}
The dynamically loaded external module has:
class A : public Base {
public:
int f() {
return 123;
}
};
extern "C" Base* make_a() {
return new A;
}
Will a system like this work on Linux, without additional steps regarding the dynamic linking? Because here only make_a
is explicitly loaded using dlsym()
, but the main module will also call A::f()
and A::~A()
, and access the v-table of A
. Will this still work even though those symbols were not explicitly loaded?
And is a similar system possible on Windows platform?
In a C++ code I'm trying to have a main module that defines a polymorphic base class, which dynamically loads derived classes for it at runtime.
So far, so good. Beware all the usual caveats - among them are:
Use the same compiler and library versions when compiling plugins. At the very least make sure the ABIs are compatible.
Link to a shared c++ runtime when doing this on windows.
windows will require ddlexport
/dllimport
attributes on declarations.
compile linux shared libraries with -fPIC
be sure to lazy-load symbol names so as to avoid conflicts (e.g. if 2 shared libs have an exported function called make_a
.
Will a system like this work on Linux, without additional steps regarding the dynamic linking?
Yes
And is a similar system possible on Windows platform?
Yes. Again, see caveats and do some research.
Some good answers here: Is there an elegant way to avoid dlsym when using dlopen in C?