Author: Hua Liang address: http://blog.csdn.net/cedricporter
We have a piece of C ++ code.
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>() );}
A piece of Python
a = DoSomethingWithA( 5 )def do(): return a.b;
We wrote in C ++
boost::python::object main_module = boost::python::import("a"); object dofoo = main_module.attr("do"); std::cout << extract<int>( dofoo() );
At this time, 12 will be output, as we thought.
The key issue is
Def ("dosomethingwitha", dosomethingwitha, Arg (""),
Return_value_policy <reference_existing_object> ());
The text below is. Translation is now available.
Return_value_policy <t>
With T one:
Reference_existing_object
Na has ve (dangerous) Approach
Boost. Python/resultconvertergenerator which
Can be used to wrap C ++ functions returning a reference or pointer to a C ++ object.
When the wrapped function is called, the value referenced by its return value is not copied.
A new Python object is created which contains an unowned u * pointer to the referent of the wrapped function's return value, and no attempt is made to ensure that the life time of the referent is at least as long as that
Of the corresponding Python object.
This class is used in the implementation of return_internal_reference. Also NULL pointer returning as none.
Copy_non_const_reference
Copy_const_reference
Boostpython V1
Approach
Manage_new_object
Boostpython/resultconvertergenerator which
Can be used to wrap C ++ functions returning a pointer to an object allocated withNew-expressionAnd expecting the caller to take responsibility for deleting that
C ++ object from heap. Boost. python will
Do it as part of Python object destruction.
Use Case:
T* factory() { return new T(); }class_<T>("T");def("Tfactory", factory, return_value_policy<manage_new_object>() );
Return_by_value
Boost. Python/resultconvertergenerator which
Can be used to wrap C ++ functions returning any reference or value type.
The return value is copied into a new Python object.