Using dlsym in c++ without extern “C”

前端 未结 3 2034
旧巷少年郎
旧巷少年郎 2021-01-14 18:11

I have a system in which I give the user a function prototype and the user has to implement it. Now, I compile this file using g++ and load it dynamically using dlopen and d

3条回答
  •  悲&欢浪女
    2021-01-14 18:47

    You can use the mangled C++ name directly.

    If you have e.g. a C++ function void my_plugin(int foo) , the C++ compiler will mangle that name. Once you know the mangled function name, you can use dlopen() on that name.

    e.g.

    # nm libmyplugin.so |grep my_plugin
    00000000 T _Z9my_plugini
    

    So here our function is named _Z9my_plugini , and you could do

     func = dlsym(handle, "_Z9my_plugini");
    

    Traditionally different compilers could mangle the name in different ways, so this could be quite fragile, thoug these days most C++ compilers will aggree opon a standard way of mangling the names on a given platform.

    However your users will be programmers, and they would normally have an understanding of exposing an entry to a dynamically loaded library as extern "C"

提交回复
热议问题