Wednesday, March 7, 2007

dynamic loading using dlopen API in C++

I just ran into this problem randomly this morning.

Think about the problem that overladed functions in C++ are in .so file and we need to load them in dynamic manner. If it is in C, it is fairly easy because we can not use the name which is already defined. One to One relationship. So, C compiler can map the symbol name as a function name in the symbol table. Nice.

Okay, in C++, simple function name will not work as a symbol name in the symbol table. One example is the overloaded functions. So, C++ compiler needs to generate other necessary information attached to the function name for symbol table. This process is called 'Name Mangling'. Unfortunately ANSI C++ does not define how to mangle names. It's all up to compiler, which means, binary level compatibility is not preserved. One SO file per system !!

Therefore, in essence, overloaded functions can not be dynamic. In addition to it, to make any C++ function dynamic, they need to be in extern "C" closure without overloading support.

Now more complicated problem occurs when we need to load a class in dynamic manner. Non-static class member function needs an instance to be in the symbol table. But, dlopen() and building an instance makes an 'chicken and egg' problem. Thinking of this problem will be my next thing for fun thought, later.

No comments: