1

I have a shared object my_lib.cc that defines in its header a class together with a factory function:

extern Foo* GetFoo():

class Foo {
 public:
  Foo() {}
  virtual ~Foo() {}
};

Now I would like application that uses the library, main.cc, to contain:

#include "my_lib.h"

class Bar : public Foo {
  // ...
};

Foo* GetFoo() {
  return new Bar();
}

The point being that when the code inside the shared object needs to create a Foo it will call the method provided by the application dynamically linking it. Is this possible to do? Typically, an application depends on symbols provided by shared objects, but is it possible to have a shared object depend on a symbol in the binary that dynamically loads it?

del
  • 1,127
  • 10
  • 16
  • My gut feeling says it should be possible if all static libraries used are the same and you use virtual mathods. Have you seen any problems? If you haven't set it up yet, you could start with [an example](https://stackoverflow.com/a/56971263/7582247) I made for another question, but it doesn't do inheritance of classes in the lib. Could be a place to start though. – Ted Lyngmo Nov 07 '19 at 21:40

1 Answers1

0

Dynamic linking goes one way, from the user of the library → to the library.

Callbacks from the library to the user are usually done through a function pointer:

In my_lib.cc:

Foo* (*MakeFoo)();

void setFooFactory(Foo* (*pMakeFoo)()) {
   MakeFoo = pMakeFoo;
}

Then in main.cc:

Foo* MakeBar() {
  return new Bar();
}

int main() {
    // load my_lib ...
    setFooFactory(MakeBar);

    // . . .
}

You can also wrap MakeFoo() into a factory class and use the C++ virtual function mechanism. I'm just demonstrating the main idea.

rustyx
  • 80,671
  • 25
  • 200
  • 267