On Mar 28, 2010, at 5:53 AM, Manohar Vanga wrote:
Hi,
I have a main program that is loading up modules dynamically at run
time. Suppose I have a function "foo" in the namespace
"Module" (Module::Foo) within the main program. I need a way to
access it from a dynamically loaded module. If I link with the
source file containing the namespaces, it will create duplicate
copies and when some variable is accessed, it will be the duplicate
and not the one from the main program.
If you compile it as a shared library and link it, it won't have
duplicate copies of global variables. It will have duplicate copies
only when you either statically link or directly link.
If I declare the function as extern in the module, the module
compiles fine but dlopen() complains that foo() is missing and
fails. Any suggestions as to how I can accomplish this?
Obviously it does. C++ name mangling prevents you from achieving this.
This is where you use interfaces. You define a pure abstract base
class that has all the required methods defined as virtual, and
implement those methods in Module.
So, in your example case, you define IFoo interface
struct IFoo
{
virtual void Foo () = 0;
};
struct Module : public Foo,SomethingElseLikeFoo
{
void Foo () { do something imp };
};
Now your main program uses IFoo everywhere without making any
reference to Module. Wherever you need to access IFoo - you register
Module as one of the classes implementing it. This way, you are
inverting the dependency of your module.
If you don't have any where to register, you can write a extern "C"
method that return you a Foo
extern "C" IFoo* GetMeFoo()
{
return new Module();
}
Now, you can use GetMeFoo from dlopen.
Thanks
Manohar
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]