Search code examples
c++dlopendlsym

dynamic loading across multiple namespaces


I am totally new to dlsym and I just reviewed C++ dlopen mini HOWTO .So please correct me if I am getting the concept and approaches wrong:

I am planning to write an application that takes shared library names as argument:

./my_app libXYZ.so

Different input libraries use their own namespaces for declaring functions that happen to have similar signatures:

libXXX.so:

namespace X {
namespace Y {
namespace Z{

 ret_t func(arg_r);

}}}

libABC.so:

namespace A {
namespace B {
namespace C{

 ret_t func(arg_r);

}}}
  • As you can see the function signatures are same.
  • Just to be clear, although the libraries are in C++, I am only talking about calling some C functions in the library, not C++ member methods.
  • The same my_app should be able to call func() without any other argument hints.

Naturally, every library contains a different mangled C++ symbol and I cannot create a single extern "C" clause that works for all(for example):

  • $^%X^&Y&^&Zfunc&^arg*&*
  • $#$A#$B&^&C&^func*&arg^&^&

The only way that comes in my mind is to get a list of library symbols, search for func sub-string (which is nasty and error prone) and formulate a extern "C" clause using macros. Can you please suggest a better solution?


Solution

  • You can't load a function without specify its namespace( unless in global namespace).

    The namespace is part of the name of the function(since its declared in that scope). In order to use it, you will have to use the using keyword or the fullname of the function (E.g namespace::some_function).

    However, if what you want is get an uniform way to call such functions, you could create a common interface to all your libraries.

    namespace A {
    namespace B {
    namespace C{
    
     ret_t func(arg_r);
    
    }}}
    
    extern "C" {
        ret_t call_func(arg_r)
        {
             return A::B::C::func(arg_r);
        }
    }
    

    and the same thing for the other library. So, in the client code of your library you only call call_func(arg_r).