Question

In my solution I obtain several object pointers from dynamically loaded DLL through imported function:

DLL side

extern "C" 
    API_EXPORT PluginBase* createInstance(const string& typeName)
{
    return TypeRegistry::instance().getTypeInstance(typeName);
}

Client side

HMODULE lib = LoadLibrary("theDll.dll");
void* proc = GetProcAddress(lib, "createInstance");
if(proc)
{           
    auto createFunc = reinterpret_cast<T* (*)(const string&)>(proc);
    shared_ptr<PluginBase> instancePtr(createFunc(theType));  
}

The actual question is what is considered more correct and/or more convenient?

  • To supply additional exported function like releaseInstance(PluginBase*) to DLL library and use it.
  • To delete instance pointer from the client code.

Regards

Was it helpful?

Solution

Provide the deleter.

It clears up any confusion about how the user is supposed to delete the object (delete? free (it comes from an extern "C" call after all)?)

And what's more, in some versions of Visual Studio, the way the runtime library works may, depending on the compiler options, mean that you cannot delete an object in one module that was newed in another.

Better than either option, though (IMO): return a shared_ptr that you already initialized with an appropriate deleter.

OTHER TIPS

For good encapsulation/secret hiding I would prefer the first approach (i.e. provide a custom delete method). You gain more flexibility, e.g. if object creation is expensive, you might have some object pool from which the createInstance method returns a free object. Instead of actually deleting an object, a simple reset might be sufficient then on release.

Depending on your scenario it might be clear that you will never need something like this (and if you are using this method only at few places). Nevertheless, as it doesn't introduce a lot of complexity to have this encapsulation, I'd probably prefer that first approach in most situations.

The details of the creation is only known to the DLL.

The client can not know what they must do to properly dispose of the object.

It would be expected that the DLL will provide a means to properly dispose of the object, even if at the time of creation there is no special reason why the client should not delete it on its own.

The way of creating and disposing may change in the future and the client's code will break if it was not given a method to dispose the object in the early versions.

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