[C++-sig] Exporting references into python

Nicholas Francis nich at users.sourceforge.net
Sun Mar 2 16:37:00 CET 2003


A newbie question regarding boost::python.

I need to make a templatized function that returns a 
boost::python::object containing a reference to an object I already 
have. Basically:

template<class T>
object convertToPython (T &obj) {
	return object (obj)
}

All classes I pass through T are already wrapped (they are also not 
copy-constructible). I tried with the code found at python.orgs wiki:

template<class T> T& identity(T& x) { return x; }
template<class T> object get_object_reference (T& x) {
	object f = make_function
		(&identity<T>, return_value_policy<reference_existing_object());
	return f(x);
}

this code gave me a compile error (on CW 8.3, Mac OS X). Apparently CW 
is convinced that the &identity<T> maps to void.

I then tried to hardcode a type just to see if it worked at all:

InputManager &identity (InputManager &x) { return x; }
object get_object_reference (InputManager &x) {
	object f = make_function (
		&identity, return_value_policy<reference_existing_object());
	return f(x);
}

This compiled, but gave me a typeerror at runtime: (No to_python 
(by-value) converter found for c++ type: InputManager)

I've seccesfully wrapped functions like this:

InputManager &GetInputManager();
BOOST_PYTHON_MODULE (Engine) {
	def (	"GetInputManager",
		&GetInputManager,
		return_value_policy<reference_existing_object()
	);
}
So it should be able to work.

Any help would be greatly appreciated....

TIA,
Nicholas





More information about the Cplusplus-sig mailing list