作者:华亮 地址:http://blog.csdn.net/cedricporter
我们有一段C++代码
A aaa;
A& DoSomethingWithA( int a )
{
aaa.Set( 12 );
return aaa;
//return &aaa;
}
//
BOOST_PYTHON_MODULE( Haha )
{
using namespace boost::python;
class_< A >( "A", "Lala" )
.def( "Set", &A::Set, arg("c") )
.def_readwrite( "b", &A::b );
def( "DoSomethingWithA", DoSomethingWithA, arg("a"), return_value_policy<reference_existing_object>() );
}
一段Python
a = DoSomethingWithA( 5 )
def do():
return a.b;
我们在C++中写道
boost::python::object main_module = boost::python::import("a");
object dofoo = main_module.attr("do");
std::cout << extract<int>( dofoo() );
此时会输出12,正如我们所想的那样。
关键问题所在是
def( "DoSomethingWithA", DoSomethingWithA, arg("a"), return_value_policy<reference_existing_object>() );
下面这段文字从http://wiki.python.org/moin/boost.python/CallPolicy#return_value_policy.3CT.3E拷贝过来的。有空再翻译了。