Yesterday, I did some research on dynamically loading shared objects and getting function pointers.
I have been told many times that sharing pointers to functions via void pointers is prohibited by the ISO C ++ standard and still remains a problem.
After reading the Johan Pettersons artitle "about the problem with dlsym" I better understand the reasons, and I also understand that this is prohibited by the standard does not mean that you absolutely should not use it. Otherwise, how do all C ++ programmers work with functions from common objects with the correct ISO C ++ code? Just guessing, I could be wrong, I am not very good at C ++.
During an experiment with my code, I found that by sharing a pointer to a structure that contains a link to the function I want to call, my compiler will not complain. I use -Wall and -pedantic when compiling.
My code is as follows:
myclass.hpp
class myclass { public: virtual void dosomething (void)=0; }
api.hpp
#include <myclass.hpp> struct API { myclass* (* func)(void); };
so.hpp
#include <iostream>
host.cpp
#include <iostream> #include <dlfcn.h> #include "myclass.hpp" #include "api.hpp" int main (void) { void * th = dlopen("./so.so", RTLD_LAZY); /* error checking was here */ #ifndef usefunction API* api = static_cast<API*>( dlsym(th, "interface") ); myclass * inst = api->make(); inst->dosomething(); #else myclass* (*func)(void) = reinterpret_cast<myclass* (*)(void)>( dlsym(th, "make") ); /* will never get to this point */ #endif return 0; }
so.so compiled so.so , I will then compile the host.cpp file.
g++ -ldl -Wall -pedantic host.cpp -o host Compiles in order, the program prints Did it. correctly Did it. at startup.
g++ -ldl -Wall -pedantic host.cpp -o host -Dusefunction Complains
In function 'int main(int, char**)': warning: ISO C++ forbids casting between pointer-to-function and pointer-to-object [enabled by default]
I know that this is just a warning, but why is it not a warning in the first case when using the structure, if at the end I can indirectly refer to a pointer to a function that is in the shared object
Talking about this, does anyone know a way to achieve all this in the absolutely correct form of ISO C ++? Does it even exist?