[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: plugin-support



Felix Kollmann wrote:

> I know that I can load functions of a shared object.
> Can I do this with classes too?
> I tryed but he wants a reference.

It is possible to load classes from a shared object using dlopen() and
friends. The trick is that using "new" probably won't work.

What I do is the following:

theclass.h

class TheClass {
public:
  static TheClass*  New();
  virtual void aMethod() = 0;
};

And in theclass.cpp:

#include <stdio.h>
#include "theclass.h"

class TheClassImpl: public TheClass {
  public:
  virtual void aMethod();
};

TheClass* TheClass::New() {
  return new TheClassImpl;
}

TheClassImpl::aMethod() {
  printf("Hello from TheClassImpl::aMethod()!\n");
}

Then, in your application, you get the symbol for the static New method
with dlsym (the name of the symbol is mangled, find it out using "nm
theclass.cpp | grep New").

I used a pure virtual in TheClass, but I think it only has to be
virtual, pure is not required. Note that you *could* have trouble
calling the inherited method from the shared object, but I think that if
you link your program with "-rdynamic" (as mentioned in the dlopen man
page), it could work.

You could even have TheClass::New in another .cpp file that you'd
statically link with the application and hide the dlopen stuff in there.

-- 
Pierre Phaneuf
Ludus Design, http://ludusdesign.com/
"First they ignore you. Then they laugh at you.
Then they fight you. Then you win." -- Gandhi