#include #include #include #include #include #include #include #include #include #include #include extern "C" { typedef int (*Function)(); } std::string dlError() { const char* error = dlerror(); return error ? std::string(error) : std::string(); } typedef boost::error_info errinfo_dlerror; struct error : virtual std::exception, virtual boost::exception {}; int loadAndRun(const char* sharedLibraryFile, const char* functionName) { int result = 0; //int flags = RTLD_LAZY; int flags = RTLD_NOW | RTLD_GLOBAL; if (void* hDl = ::dlopen(sharedLibraryFile, flags)) { boost::shared_ptr hDlAuto(hDl, &::dlclose); if (void *hFunction = ::dlsym(hDl, functionName)) { Function pFunction = reinterpret_cast(hFunction); result = (*pFunction)(); } else { BOOST_THROW_EXCEPTION(error() << boost::errinfo_api_function("dlsym") << errinfo_dlerror(dlError())); } } else { BOOST_THROW_EXCEPTION(error() << boost::errinfo_api_function("dlopen") << errinfo_dlerror(dlError())); } return result; } int main(void) { try { for (std::size_t i = 0; i < 10000; ++i) { int result = loadAndRun("./libfunction.so", "function"); if (result != 0) { std::cerr << "Run error: " << result << std::endl; } if (i % 100 == 0) { std::cout << "Call: " << i << std::endl; } } } catch (std::exception& e) { std::cerr << "Error: " << boost::current_exception_diagnostic_information() << std::endl; } return 0; }