2012-06-18 30 views
0

使用Boost.Python的,我似乎无法能够绑定返回一个const char任何功能*例如:不能绑定的函数,返回为const char *

class Bar 
{ 
private: 
    int x; 
public: 
    Bar():x(0){} 
    Bar(int x) : x(x) {} 
    int get_x() const { return x; } 
    void set_x(int x) { this->x = x; } 
    const char *get_str(){return "hello";} 
}; 

BOOST_PYTHON_MODULE(internal_refs) 
{ 
    class_<Bar>("Bar") 
     .def("get_x", &Bar::get_x) 
     .def("set_x", &Bar::set_x) 
     .def("get_str", &Bar::get_str, return_internal_reference<>()) 
     ; 
} 

我得到以下错误:

/usr/local/include/boost/python/object/make_instance.hpp:27:9: error: no matching function for call to ‘assertion_failed(mpl_::failed************ boost::mpl::or_<boost::is_class<char>, boost::is_union<char>, mpl_::bool_<false>, mpl_::bool_<false>, mpl_::bool_<false> >::************)’ 

回答

3

有了boost 1.50,我可以返回const char*而无需指定CallPolicy。您收到的编译错误是静态断言,表明return_internal_reference被设计为用于类或联合的类型。在这种情况下,这两者都不是。

BOOST_PYTHON_MODULE(internal_refs) 
{ 
    class_<Bar>("Bar") 
     .def("get_x", &Bar::get_x) 
     .def("set_x", &Bar::set_x) 
     .def("get_str", &Bar::get_str) 
     ; 
} 
python 
>>> from internal_refs import Bar 
>>> b = Bar() 
>>> b.get_str() 
'hello' 
>>> type(b.get_str()) 
<type 'str'>
+0

烨的作品,所以我并不需要为const char回报的政策*?但是如何提升知道不解放?我的意思是安全吗?我已阅读关于退货政策,但我仍然不确定何时使用每一个? – iabdalkader

+1

它应该是安全的。 'boost :: python'正在处理它知道将是不可变的类型的底层细节。在这种情况下,它将分配一个“Py_String”对象,填充它,然后允许Python进行管理。 [Here](http://stackoverflow.com/a/11144752/1053968)是一个解释,可以提供一些见解,为什么'return_internal_reference'需要类或联合类型。 –

+0

谢谢,我会奖励你的答案赏金,但它说我必须等21个小时,明天会这样做,再次感谢你的帮助。 – iabdalkader

相关问题