Boost Python包装C++関数Python使用時の戻り値が参照タイプのソリューションです。


作者:華亮       住所: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(「DomSomethingWithA」、DonmethingWithA、arg(「a」)、return Huvalueupolicy<referencegaobject>;
次の文字はhttp://wiki.python.org/moin/boost.python/CallPolicy#return_value_policy.3 CT.3 Eからコピーしました。暇があったらまた翻訳します。
return_value_policy
with T one of:
reference_existing_object
なïve(dangerous)approach
book.python/ResultConverterGenerator which can be used to wrap C++functions returning a reference or pointer to a C+object.
When the wrapped function is caled,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のatempt is to ensure that the liferent is the least of the
This class is used in the implemention of return_インターナールreference. Also NULL pointer returning as None.
copy_non_constreference
copy_constreference
ボストン v 1 appach
マンゲnew_object
boost Python/ResultConverterGenerator which can be used to wrap C++functions returning a pointer to an object allocated with a new-expression and expecting the caler to take reponsibility for deleting that C++object from heap. book.python will do it as part of Python object destruct.
Use case:
T* factory() { return new T(); }

class_<T>("T");

def("Tfactory", factory, return_value_policy<manage_new_object>() );
return_by_value
book.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.