【发布时间】:2015-02-12 23:20:35
【问题描述】:
当使用动态库时,我知道我们应该只跨边界传递普通的旧数据结构。那么我们可以传递一个指向 base 的指针吗?
我的想法是应用程序和库都可以知道一个通用接口(纯虚拟方法,= 0)。 该库可以实例化该接口的子类型, 并且应用程序可以使用它。
例如,下面的 sn-p 安全吗?
// file interface.h
class IPrinter{
virtual void print(std::string str) = 0;
};
-
// file main.cpp
int main(){
//load plugin...
IPrinter* printer = plugin_get_printer();
printer->print( std::string{"hello"} );
}
-
// file plugin.cpp (compiled by another compiler)
IPrinter* plugin_get_printer(){
return new PrinterImpl{};
}
【问题讨论】:
-
如果你在 Windows 上,你基本上是在重新设计 COM。它以足够优雅但更重要的是有据可查的方式解决了您正在谈论的问题。不过,我对非 Windows 平台的了解还不够多,无法对此发表评论。