【发布时间】:2015-10-03 02:52:46
【问题描述】:
假设我有一个这样定义的抽象基类:
interface.hpp
#ifndef INTERFACE_HPP
#define INTERFACE_HPP 1
class interface{
public:
virtual void func() = 0;
};
#endif // INTERFACE_HPP
然后我将一个翻译单元test.cpp编译成一个共享对象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;
}
如果我在可执行文件中打开该共享对象并尝试像这样调用get_interface:
#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);
}
(假装我做了错误检查)
行为是否明确定义?还是我假设这将始终有效,从而踩到自己的脚趾?
请记住,我只会使用 clang 和 gcc
【问题讨论】:
-
如果您使用的是相同的编译器,那么我认为这不会出错。我刚刚将您的示例移植到 msvc (2015rc),它也可以在那里工作。