, ++ - , . ( ) .
, .
factory, . , factory factory . , :
#include <memory>
struct PlugIn // interface
{
virtual ~PlugIn() = 0;
virtual void doSomething() = 0;
};
extern "C" {
typedef std::auto_ptr<PlugIn> PlugInFactoryFn();
std::auto_ptr<PlugIn> createPlugIn();
}
#include "plugin.h"
#include <assert.h>
#include <dlfcn.h>
std::auto_ptr<PlugIn> loadPlugIn(char const* filename)
{
void* so = dlopen(filename, RTLD_NOW | RTLD_LOCAL);
assert(so);
void* factory_function = dlsym(so, "createPlugIn");
assert(factory_function);
return reinterpret_cast<PlugInFactoryFn*>(factory_function)();
}
int main()
{
std::auto_ptr<PlugIn> a(loadPlugIn("a.so"));
std::auto_ptr<PlugIn> b(loadPlugIn("b.so"));
a->doSomething();
b->doSomething();
}