Say I have a abstract base class defined like so:
interface.hpp
#ifndef INTERFACE_HPP
#define INTERFACE_HPP 1
class interface{
public:
virtual void func() = 0;
};
#endif // INTERFACE_HPP
Then I compile a translation unit test.cpp
into a shared object test.so
:
test.cpp
#include "interface.hpp"
#include <iostream>
class test_interface: public interface{
public:
void func(){std::cout << "test_interface::func() called\n";}
};
extern "C"
interface &get_interface(){
static test_interface test;
return test;
}
If I open that shared object in an executable and try to call get_interface
like this:
#include <dlfcn.h>
#include "interface.hpp"
int main(){
void *handle = dlopen("test.so", RTLD_LAZY);
void *func = dlsym(handle, "get_interface");
interface &i = reinterpret_cast<interface &(*)()>(func)();
i.func(); // print "test_interface::func() called"
dlclose(handle);
}
(just pretend I did error checking)
Is the behaviour well defined? Or am I stepping on my own toes by assuming this will always work?
Keep in mind I will only ever be using clang and gcc