This is my attempt to load shared library on linux (and may be mac - did not test yet)
I am interested if I am implementing everything correctly and if I can really use my function in a loop like that.
I deliberately use iostream, because it is part of the C++ library and it wont work unless library is linked (-lstdc++)
Thanks in advance.
base.h
#ifndef BASE_H__
#define BASE_H__
struct Base{
virtual int do_something() = 0;
virtual ~Base(){
}
};
#endif
main.cpp
#include "base.h"
#include <dlfcn.h>
#include <iostream>
#include <memory>
#include <optional>
template<typename T, typename... Args>
std::optional<T> dl_exec(const char *filename, const char *symbol, Args... args){
constexpr bool show_errors = true;
auto err = [show_errors](const char *msg){
if constexpr(show_errors){
std::cerr << "Error Message: " << msg << '\n';
std::cerr << "Error System: " << dlerror() << '\n';
}
return std::optional<T>{};
};
void *handle = dlopen(filename, RTLD_LAZY);
if (!handle)
return err("Bad filename");
void *fp = dlsym(handle, symbol);
if (!fp)
return err("Bad symbol name");
auto f = ( T (*)(Args...) ) fp;
return f(args...);
}
int main(int argc, char **argv){
for(int i = 0; i < 10; ++i){
auto o = dl_exec<Base *, int>(argv[1], "create_class", i);
if (!o){
std::cerr << "Error detected" << '\n';
return 1;
}
std::unique_ptr<Base> b{ *o };
std::cout << "result " << b->do_something() << '\n';
}
}
dynamic1.cpp
#include "base.h"
#include <iostream>
struct Dynamic : public Base{
int do_something() final{
std::cout << "It works!!!" << '\n';
return 42;
}
};
extern "C" {
Base *create_class(int){
return new Dynamic();
}
}
// g++ -fPIC -shared dynamic1.cc -o dynamic1.so
dynamic2.cpp
#include "base.h"
#include <iostream>
struct Dynamic : public Base{
Dynamic(int a) : a(a){
}
int do_something() final{
std::cout << "It works 100%!!!" << '\n';
return 100 + a;
}
int a;
};
extern "C" {
Base *create_class(int a){
return new Dynamic(a);
}
}
// g++ -fPIC -shared dynamic2.cc -o dynamic2.so
Example usage
[nmmm@zenbook DL]$ gcc main.cpp -lstdc++
[nmmm@zenbook DL]$ g++ -fPIC -shared dynamic1.cpp -o dynamic1.so
[nmmm@zenbook DL]$ g++ -fPIC -shared dynamic2.cpp -o dynamic2.so
[nmmm@zenbook DL]$ ./a.out ./dynamic1.so
result It works!!!
42
result It works!!!
42
result It works!!!
42
result It works!!!
42
result It works!!!
42
result It works!!!
42
result It works!!!
42
result It works!!!
42
result It works!!!
42
result It works!!!
42
[nmmm@zenbook DL]$ ./a.out ./dynamic2.so
result It works 100%!!!
100
result It works 100%!!!
101
result It works 100%!!!
102
result It works 100%!!!
103
result It works 100%!!!
104
result It works 100%!!!
105
result It works 100%!!!
106
result It works 100%!!!
107
result It works 100%!!!
108
result It works 100%!!!
109