return_existing_py_object policy
Hi, I made myself policy that searches for existing python object holding the returned from a function pointer or reference and then returns it to python. I am posting it in case anybody is interested. It is declared like that: template < class BackRef = BackReference , class FallbackPolicies = detail::default_fallback_policy , class Base = default_call_policies > struct return_existing_py_object; The BackRef parameter is the class that holds self pointer. So if you have class A{ //A has to be polymorphic virual void f(){} }; class A *func(); struct A_wrap:A { A_wrap(PyObject *s):self(s){} PyObject *self; }; class_<A,A_wrap>("A"); then you can do def("func", &func, return_existing_py_object<A_wrap>()); The FallbackPolicies parameter is used in case no python object object holding the result is found. The default is to raise an error. I also use it with return_internal_reference<>. The default BackReference class can bu used for defining wrapper classes, like struct A_wrap: A, BackReference { A_wrap(PyObject *s):BackReference(s){} }; in which case the def call can look like that: def("func", &func, return_existing_py_object<>()); -- Nikolay Mladenov Sitius Automation Inc. www.sitius.com
participants (1)
-
Nikolay Mladenov