【问题标题】:Passing shared_ptr to another python module将 shared_ptr 传递给另一个 python 模块
【发布时间】:2015-06-16 14:50:09
【问题描述】:

我用boost python做了一个python模块。

它是一个日志模块,日志消费者看起来像这样。基本上有一个抽象接口,文件记录器就是从那里派生出来的。

class DIAGNOSTICS_API ISink : public boost::enable_shared_from_this<ISink>
{
public:
    virtual ~ISink();
    virtual void AddEntry(Entry& logEntry) = 0;
    virtual bool ShallLog(const std::string& domain, Severity severity) = 0;
};

class DIAGNOSTICS_API DomainRulesBasedSink : public ISink
{
    .........
}

class DIAGNOSTICS_API FileSink : public DomainRulesBasedSink
{
    .........
}

这段代码被打包到一个python模块中。

boost::python::class_<Log::ISinkRealizer, boost::shared_ptr<Log::ISinkRealizer>, boost::noncopyable>("ISink", boost::python::no_init)
    .def("AddEntry", boost::python::pure_virtual(&Log::ISinkRealizer::AddEntry))
    .def("ShallLog", boost::python::pure_virtual(&Log::ISinkRealizer::ShallLog));

boost::python::class_<Log::FileSink, boost::shared_ptr<Log::FileSink>, boost::python::bases<Log::ISink>, boost::noncopyable>
    ("FileSink", boost::python::init<const std::string&>())
    .def("AddDomain", &Log::FileSink::AddDomain)
    .def("Create", &Log::FileSink::Create)
    .staticmethod("Create");

boost::python::class_<Log::Source, boost::shared_ptr<Log::Source>>("Source", boost::python::init<const std::string&>())
    .def(boost::python::init<const std::string&, boost::shared_ptr<Log::ISink>>())
    .def("SetSink", &Log::Source::SetSink);

当我在 python 中使用实例化 FileSink 时,我可以将它放入同一模块中的类的构造函数中。

但是,当我尝试将相同的实例插入到另一个模块中的另一个类中时,它就不起作用了。

Python argument types in
    SensorController.__init__(SensorController, FileSink)
did not match C++ signature:
    __init__(struct _object * __ptr64, class boost::shared_ptr<class Log::ISink>)

我很确定 python 通过 shared_ptr 创建 FileSink,但是当我想将它提供给另一个模块(SensorController 类)中的构造函数时,它会看到“FileSink”而不是“boost::shared_ptr”

我的 shared_ptr 对象不仅对实例化此类的模块可见,而且对其他模块可见。

【问题讨论】:

  • 这个link 看起来与我的问题非常相似。我将尝试将python构建为动态库并再次测试。基本上然后问题 - 据我了解 - 每次静态库链接到模块时,它都会获得自己的类型转换寄存器,并且不会在模块之间共享。在 DLL 的情况下,它是共享的。

标签: python boost-python


【解决方案1】:

问题正如link 中所解释的那样。当 Boost Python 用作静态库时,类型转换注册表(如何在 python 对象和 C++ 对象之间进行转换)复制与 boost python 链接的次数一样多。但是,当它作为动态库链接时,它只有一个类型转换注册表,并且所有 python 模块都可以看到其他类型。

【讨论】:

    猜你喜欢
    • 2015-03-21
    • 2013-01-16
    • 1970-01-01
    • 2021-07-13
    • 2012-07-04
    • 1970-01-01
    • 2014-01-05
    • 1970-01-01
    • 2020-03-30
    相关资源
    最近更新 更多