Re: Design Pattern for Dynamic Class Loading
digz wrote:
Apologies if this is the wrong group for this question. I want to
design an interface , where for a custom functionality , the client
writes a new class with the function implementation and then puts the
name of the Class as a configuration parameter or something and then
the main program loads the new class like a module and the client can
now write code using the new Functions. I suppose this problem has
been solved before , if so what is the best way to do this .
Since C++ is a statically typed language, the types need to be known to
the compiler at the compile-time. Most of what you describe is possible
and serves as the foundation of any plug-in architecture programmed in
C++. You can probably look into Mozilla or any other open-source
projects that have plug-ins, or just read about them in books that have
been written on the subject.
The usual way to provide what you're asking about is to designate some
function[s] in your system to be "factories". All the functionality is
structured based on the existing classes (like your 'printInt') struct,
and the plug-ins are allowed to provide their implementation *and* the
necessary factory function which instantiates the derived class and
returns the pointer to the base. The system then stores the pointer to
the base class and when the virtual function (yes, the operator() needs
to be 'virtual' in that case) is called, the custom implementation is
going to be invoked.
OOH, plug-in architectures are very common nowadays and described in
many places (and you can probably find some in the news archives), OTOH,
it's not a simple 10-line coding exercise, so, IMHO it does not make
sense to spend time describing it here. I strongly recommend you to
look in the available information sources, the web should be the first
thing to look through.
Thanks
Digz
Example :
I have already provided him with
printInt.cc :
struct printInt {
void operator ()(int i)
{ Print(i); }
Now the user wants to write a class and start using the implementation
in the class
printDbl.cc which is
struct printDbl{
void operator ()(double i)
{ Print(i); }
int main()
{
Config* c = readConfig();
For name in c->classNames():
Load( name ) ;
printDbl pd;
pd(1.0);
}
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask