1

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?

tmlen
  • 8,533
  • 5
  • 31
  • 84
  • Plugins on Windows work differently, and could need `dllimport` and `dllexport` annotations for functions of your main program used by plugins. That makes a *huge* difference. BTW, your system works on Linux because you linked the main program with `-rdynamic`. Read Levine's [Linkers and loaders](https://www.iecc.com/linkers/) book. Be aware of name mangling. – Basile Starynkevitch Sep 27 '18 at 14:13
  • 1
    standard library has to be linked dynamically for dll and host application, otherwise each part will have own heap and you can have problems during cleanup. – Marek R Sep 27 '18 at 14:15
  • 1
    "_call A::f() and A::~A(),_" Specifically, you will use the deleting `A::~A()`, the function performing `delete a_ptr;` virtually. It's a different destructor entry. (Compile with vtable printing. Or check the asm code.) – curiousguy Sep 27 '18 at 19:08

1 Answers1

1

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?

Richard Hodges
  • 68,278
  • 7
  • 90
  • 142