Question

TL;DR: Is it possible to load a class object from a library at runtime, close the library and then use the object as a "normal" object (after closing)?

I am trying to implement a plug-in system with some sort of "hot swap" functionality. Suppose my program expects a doSomething() function from its plugins. My idea would be to scan the fileystem for any libs in a specific folder, extract the functions and then close the lib (before using the functions!). This way, a monitor thread could just monitor changes on the filesystem and reset the function pointer in case something changed and thus plug-ins could be "hot swapped".

I believe that the function pointer would become invalid as soon as I close the library (Is that so?). Therefore my idea is to let the library return a copy of an object which does the desired functionality. In this case, I would call the lib to create the object before closing it and save the copy of the object in my program. However, since the object can use other objects/functions of the library, I am not sure if this would work, since these objects/functions would not be available, would they?

Was it helpful?

Solution

  1. You cannot copy the object and close the library, since only data, but not the code of those objects is copied. Instead of it OS loads code of the library to the memory and all function pointers points to this region of memory. What will be if OS unloads the library?

  2. You can implement something like this. You can have a Proxy object that contains a pointer to current loaded implementation. If a new library is detected, you can load new library, create instance of a new implementation, delete old instance of implementation, close old library. In this way you implement a "hot swap" mechanism and avoid problem with shared libraries code.

  3. If you chose way described in item 2, beware of concurrency problems (what if another thread is scheduled when old implementation is deleted, but before the pointer is changed?).

OTHER TIPS

An object is data, not code. A copy of an object is a copy of the data, but it still refers to the original code. As soon as you unload a dynamic library, its code is gone from memory, and any objects still referencing that code (i.e. of a type provided by the library) will be in trouble as soon as they are asked to execute a member function (such as the destructor).

So no, it's not possible to unload a library and keep using its code.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top