Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to define a function pointer to a constructor?

I'm using shared library with explicit linking (loading shared lib with dlopen) in order to implement plugin pattern in C++.

Is it possible to define a function pointer to a constructor of a class defined in the shared library or I would have to define factory method, within shared lib, that would instantiate (and initialize) object of a class from shared lib? Of course in my main app, then, I would define a function pointer to a factory method, and that method would return an instance of the class I need.

Cheers

like image 920
dragan.stepanovic Avatar asked Mar 11 '26 14:03

dragan.stepanovic


2 Answers

The answer to the question is no, you can not define a member or function pointer to the constructor.

For dlopen, you need to provide a function with c linkage and load it dynamically, which you can use to create the objects, and you also need another function to delete objects.

More about it here

like image 104
BЈовић Avatar answered Mar 14 '26 03:03

BЈовић


You'd need to be aware of the name mangling problems when fetching pointers with dlsym(). It's not a good idea to rely on some specific mangling method, they're all too diverse. So the only reasonable thing to do is to expose your plugin interface as extern "C" { ... }, with factory function wrappers over constructors.

like image 45
SK-logic Avatar answered Mar 14 '26 05:03

SK-logic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!