Suppose I want to get the reference to some global / internal c++ object, one method is to declare function with boost::python::return_value_policy<reference_existing_object>()
.
Both GetGlobalObjectA
and GetGlobalObjectB
return the reference to the original c++ object without create a new copy;
But how to make GetGlobalObjectByID
return a ref to the existing c++ object?
struct A { uint32_t value; }; struct B { uint64_t value; }; A globalA; B globalB; boost::python::object GetGlobalObjectByID(int id) { // boost::python::object will return a new copy of C++ object, not the global one. if (id == 1) return boost::python::object(&globalA); else if (id == 2) return boost::python::object(&globalB); else return boost::python::object(nullptr); } A& GetGlobalObjectA() { return globalA; } B& GetGlobalObjectB() { return globalB; } BOOST_PYTHON_MODULE(myModule) { using namespace boost::python; class_<A>("A"); class_<B>("B"); def("GetGlobalObjectByID", GetGlobalObjectByID); def("GetGlobalObjectA", GetGlobalObjectA, return_value_policy<reference_existing_object>()); def("GetGlobalObjectB", GetGlobalObjectB, return_value_policy<reference_existing_object>()); }