简体   繁体   中英

Shared object depending on symbol in code dynamically linking it?

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM