簡體   English   中英

使用std :: shared_ptr的Boost.Python和Polymorphic Behavior

[英]Boost.Python and Polymorphic Behaviour with std::shared_ptr

我想知道當使用std::shared_ptr而不是boost::shared_ptr時,下面的AB類如何在python中以多態方式工作?

struct A
{
    virtual ~A() {}
};

struct B : A
{
    B() {}
    virtual ~B() {}
};

void f(const std::shared_ptr<A>& ptr)
{}

BOOST_PYTHON_MODULE(test)
{
    class_<A, boost::noncopyable>("A", no_init);

    class_<B, std::shared_ptr<B>, bases<A>>("B")
        .def(init<>());

    def("f", f);
}

我知道必須為std::shared_ptr定義boost::get_pointer方法,所以我確保在#include <boost/python.hpp>之前存在以下行:

namespace boost {
template<class T> const T* get_pointer(const std::shared_ptr<T>& p)
{
    return p.get();
}

template<class T> T* get_pointer(std::shared_ptr<T>& p)
{
    return p.get();
}
} // namespace boost

現在,在python中我嘗試:

>>> from test import *
>>> b = B()
>>> f(b)
Traceback (most recent call last):
  File "<console>", line 1, in <module>
ArgumentError: Python argument types in
    test.f(B)
did not match C++ signature:
    f(std::shared_ptr<A>)

注意:上面的代碼適用於boost::shared_ptr ,但我想堅持使用C ++ 11類型。

謝謝。

Boost.Python內置了特殊的魔法來識別boost :: shared_ptr。 它目前不識別std :: shared_ptr。 現在,只是皺眉並使用boost :: shared_ptr。

我做了一次std::shared_ptr與boost :: python IIRC一起工作,在你寫的時候使用get_pointer (相關評論在這里 )。 我的猜測是你需要class_<A,std::shared_ptr<A>,...>因為那是你的函數作為參數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM