2012-04-17 80 views
3

我想知道如何使用std::shared_ptr而不是boost::shared_ptr在下面的類AB python多態工作?Boost.Python和多態行爲與std :: shared_ptr

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類型。

謝謝。

+0

如果有人絆倒了這一點,@eudoxos在下面有一個工作解決方案。你不需要切換到'boost :: shared_ptr'。 – 2015-05-21 15:41:41

回答

0

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

+0

Boost.python可以通過get_pointer使用std :: shared_ptr,你寫的是不正確的。 – eudoxos 2012-04-18 20:52:45

+2

std :: shared_ptr最近才被支持。在提升1.47這不是在那裏。 – mirk 2012-04-19 13:47:04

0

我寫過一次std::shared_ptr,使用boost :: python IIRC,使用get_pointer。 (相關評論是here)。我的猜測是你需要有class_<A,std::shared_ptr<A>,...>,因爲這是你的函數作爲參數。

+0

我試過'class_ >(「A」)',但沒有運氣。它編譯得很好,但在python中失敗。 – Allan 2012-04-19 13:29:58

+0

你真的發佈一個**真正的**代碼?沒有一些修改,我無法編譯它。能不能請你? – eudoxos 2012-04-20 07:30:05

+0

我發佈在C++ - sig論壇[here](http://thread.gmane.org/gmane.comp.python.c++/15759)上,因爲它看起來像是一個錯誤或至少意外的行爲。讓我們來看看boost:; python傢伙們說的。 – eudoxos 2012-04-20 08:02:17

相關問題