Am 28.05.2012 13:27, schrieb Lex Trotman:
This doesn't actually call the C++ constructors/destructors in the way they would be in normally be if the plugin had been statically linked.
This simply labels a C function to be called at dlopen time. It may be used to do some initialisation, but you would have to manually call each constructor, ... too error prone, Franks advice to create everything dynamically is sound.
I meant to say that global/static constructors/destructors are in fact called when a library is dlopened(), regardless of the language of calling code.
Anyway, I thought an example illustrates it better:
$ cat test.c #include <dlfcn.h> #include <stdlib.h> #include <stdio.h> int main() { void* h = dlopen("/tmp/foo/libtestcpp.so", RTLD_NOW); if (!h) { printf("no lib %s\n", dlerror()); exit(-1); } void (*fn)(void) = dlsym(h, "hello"); if (!fn) exit(-2); fn(); dlclose(h); return 0; }
$ gcc -o test test.c -ldl -g
$ cat test.cpp #include <iostream>
namespace std {
class Test { public: Test() { cout << "Hello from Test" << endl; } ~Test() { cout << "Bye from Test" << endl; } };
static Test test;
}
extern "C" {
#include <stdio.h>
void hello(void) { printf("hello from extern C function\n"); }
}
$ gcc -o libtestcpp.so -shared -fPIC test.cpp -g -lstdc++ -Wl,--no-undefined
$ ./test Hello from Test hello from extern C function Bye from Test
FWIW, does anyone know why I needed to link libstdc++ explicitely in my testing?
Best regards.