diff --git a/extclass_demo.cpp b/extclass_demo.cpp index 7efaff69..634cfe14 100644 --- a/extclass_demo.cpp +++ b/extclass_demo.cpp @@ -616,6 +616,42 @@ void vd_push_back(std::vector& vd, const double& x) vd.push_back(x); } +/************************************************************/ +/* */ +/* What if I want to return a pointer? */ +/* */ +/************************************************************/ + +// +// This example exposes the pointer by copying its referent +// +struct Record { + Record(int x) : value(x){} + int value; +}; + +const Record* get_record() +{ + static Record v(1234); + return &v; +} + +template class py::ExtensionClass; // explicitly instantiate + +} // namespace extclass_demo + +#ifndef PY_NO_INLINE_FRIENDS_IN_NAMESPACE +namespace py { +#endif +inline PyObject* to_python(const extclass_demo::Record* p) +{ + return to_python(*p); +} +#ifndef PY_NO_INLINE_FRIENDS_IN_NAMESPACE +} +#endif + +namespace extclass_demo { /************************************************************/ /* */ /* init the module */ @@ -624,6 +660,10 @@ void vd_push_back(std::vector& vd, const double& x) void init_module(py::Module& m) { + m.def(get_record, "get_record"); + py::ClassWrapper record_class(m, "Record"); + record_class.def_readonly(&Record::value, "value"); + m.def(sizelist, "sizelist"); py::ClassWrapper > vector_double(m, "vector_double"); diff --git a/test_extclass.py b/test_extclass.py index e7ba6e0b..fb51af9e 100644 --- a/test_extclass.py +++ b/test_extclass.py @@ -841,6 +841,16 @@ test inheritB2 'B2::inheritB2' >>> db2.inheritB2() 'B2::inheritB2' + +=============================================================== +test methodologies for wrapping functions that return a pointer + + >>> get_record().value + 1234 + + In this methodology, the referent is copied + >>> get_record() == get_record() + 0 ''' from demo import *