C ++插件:它是确定通态对象? [英] c++ plugin : Is it ok to pass polymorphic objects?

查看:137
本文介绍了C ++插件:它是确定通态对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用动态库,我明白,我们应该只通过跨边界普通旧式数据结构。因此,我们可以传递一个指针到基地?

我的想法是,应用程序和库既能知道一个共同的接口(纯虚方法,= 0)。
该库可以实例化界面的一种亚型,
而应用程序可以使用它。

例如,为下面的代码片断安全吗?

  //文件interface.h类IPrinter {
    虚拟无效打印(STD ::字符串str)= 0;
 };

-

  //文件的main.cpp诠释主(){
    //加载插件...
    IPrinter *打印机= plugin_get_printer();
    打印机相>打印(标准::字符串{你好});
}

-

  //文件plugin.cpp(由另一个编译器编译)IPrinter * plugin_get_printer(){
    返回新PrinterImpl {};
}


解决方案

这片段是不是安全的:


  • 您的DLL边界双方不使用相同的编译器。这意味着,名称重整(对于函数名)和的虚表布局(虚拟函数)可能是不一样的(具体执行。


  • 两边的堆也可以不同的方式管理,因此你可以与你的对象删除的风险,如果它不是在DLL中完成的。


文章 presents非常好,二进制兼容的接口的主要挑战。

但是您也可以通过镜子指针的另一边,作为一个POD的一部分,只要其他部分没有我们它由iself(f.ex:您的应用程序将指针传递到配置对象该DLL。后来另一个DLL FUNCT返回该指针您的应用程序。然后,您的应用程序可以使用它作为预期(至少如果它不是一个指向本地对象已不存在)。

When using dynamic libraries, I understand that we should only pass Plain Old Data-structures across boundaries. So can we pass a pointer to base ?

My idea is that the application and the library could both be aware of a common Interface (pure virtual method, = 0). The library could instantiate a subtype of that Interface, And the application could use it.

For instance, is the following snippet safe ?

// 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{};
}

解决方案

This snippet is not safe:

  • the two sides of your DLL boundaries do not use the same compiler. This means that the name mangling (for function names) and the vtable layout (for virtual functions) might not be the same (implementation specific.

  • the heap on both sides may also be managed differently, thus you have risks related to the deleting of your object if it's not done in the DLL.

This article presents very well the main challenges with binary compatible interfaces.

You may however pass to the other side of the mirror a pointer, as part of a POD as long as the other part doesn't us it by iself (f.ex: your app passes a pointer to a configuration object to the DLL. Later another DLL funct returns that pointer to your app. Your app can then use it as expected (at least if it wasn't a pointer to a local object that no longer exists) .

这篇关于C ++插件:它是确定通态对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆