diff --git a/pybindgen/cppclass_typehandlers.py b/pybindgen/cppclass_typehandlers.py index fa15f87..176bd4c 100644 --- a/pybindgen/cppclass_typehandlers.py +++ b/pybindgen/cppclass_typehandlers.py @@ -653,25 +653,6 @@ class CppClassRefReturnValue(CppClassReturnValueBase): wrapper.after_call.write_code('%s = *%s->obj;' % (self.value, name)) -def _add_ward(wrapper, custodian, ward): - wards = wrapper.declarations.declare_variable( - 'PyObject*', 'wards') - wrapper.after_call.write_code( - "%(wards)s = PyObject_GetAttrString(%(custodian)s, (char *) \"__wards__\");" - % vars()) - wrapper.after_call.write_code( - "if (%(wards)s == NULL) {\n" - " PyErr_Clear();\n" - " %(wards)s = PyList_New(0);\n" - " PyObject_SetAttrString(%(custodian)s, (char *) \"__wards__\", %(wards)s);\n" - "}" % vars()) - wrapper.after_call.write_code( - "if (!PySequence_Contains(%(wards)s, %(ward)s))\n" - " PyList_Append(%(wards)s, %(ward)s);" % dict(wards=wards, ward=ward)) - wrapper.after_call.add_cleanup_code("Py_DECREF(%s);" % wards) - - - class CppClassPtrParameter(CppClassParameterBase): "Class* handlers" CTYPES = [] @@ -1045,19 +1026,6 @@ class CppClassPtrReturnValue(CppClassReturnValueBase): # return the value wrapper.build_params.add_parameter("N", [py_name], prepend=True) - - # custodian/ward stuff... - if self.custodian is None: - pass - elif self.custodian == 0: - assert wrapper.class_.allow_subclassing - _add_ward(wrapper, '((PyObject *) self)', "((PyObject *) %s)" % py_name) - else: - assert self.custodian > 0 - param = wrapper.parameters[self.custodian - 1] - assert param.cpp_class.allow_subclassing - assert isinstance(param, CppClassParameterBase) - _add_ward(wrapper, "((PyObject *) %s)" % param.py_name, "((PyObject *) %s)" % py_name) def convert_python_to_c(self, wrapper): @@ -1095,33 +1063,72 @@ class CppClassPtrReturnValue(CppClassReturnValueBase): warnings.warn("Returning shared pointers is dangerous!" " The C++ API should be redesigned " "to avoid this situation.") + + +## +## Core of the custodians-and-wards implementation +## + +def scan_custodians_and_wards(wrapper): + """ + Scans the return value and parameters for custodian/ward options, + converts them to add_custodian_and_ward API calls. Wrappers that + implement custodian_and_ward are: CppMethod, Function, and + CppConstructor. + """ + assert hasattr(wrapper, "add_custodian_and_ward") + + for num, param in enumerate(wrapper.parameters): + custodian = getattr(param, 'custodian', None) + if custodian is not None: + wrapper.add_custodian_and_ward(custodian, num+1) + + custodian = getattr(wrapper.return_value, 'custodian', None) + if custodian is not None: + wrapper.add_custodian_and_ward(custodian, -1) + + + +def _add_ward(code_block, custodian, ward): + wards = code_block.declare_variable( + 'PyObject*', 'wards') + code_block.write_code( + "%(wards)s = PyObject_GetAttrString(%(custodian)s, (char *) \"__wards__\");" + % vars()) + code_block.write_code( + "if (%(wards)s == NULL) {\n" + " PyErr_Clear();\n" + " %(wards)s = PyList_New(0);\n" + " PyObject_SetAttrString(%(custodian)s, (char *) \"__wards__\", %(wards)s);\n" + "}" % vars()) + code_block.write_code( + "if (!PySequence_Contains(%(wards)s, %(ward)s))\n" + " PyList_Append(%(wards)s, %(ward)s);" % dict(wards=wards, ward=ward)) + code_block.add_cleanup_code("Py_DECREF(%s);" % wards) - -def implement_parameter_custodians(wrapper): - """ - Generate the necessary code to implement the custodian= option - of C++ class parameters. It accepts a Forward Wrapper as argument. - """ - assert isinstance(wrapper, ForwardWrapperBase) - for param in wrapper.parameters: - if not isinstance(param, CppClassPtrParameter): - continue - if param.custodian is None: - continue - if param.custodian == -1: # the custodian is the return value - assert wrapper.return_value.cpp_class.allow_subclassing - _add_ward(wrapper, "((PyObject *) %s)" % wrapper.return_value.py_name, - "((PyObject *) %s)" % param.py_name) - elif param.custodian == 0: # the custodian is the method self - assert wrapper.class_.allow_subclassing - _add_ward(wrapper, "((PyObject *) self)", - "((PyObject *) %s)" % param.py_name) - else: # the custodian is another parameter - assert param.custodian > 0 - custodian_param = wrapper.parameters[param.custodian - 1] - assert custodian_param.cpp_class.allow_subclassing - _add_ward(wrapper, "((PyObject *) %s)" % custodian_param.py_name, - "((PyObject *) %s)" % param.py_name) +def _get_custodian_or_ward(wrapper, num): + if num == -1: + assert wrapper.return_value.py_name is not None + return "((PyObject *) %s)" % wrapper.return_value.py_name + elif num == 0: + return "((PyObject *) self)" + else: + assert wrapper.parameters[num-1].py_name is not None + return "((PyObject *) %s)" % wrapper.parameters[num-1].py_name +def implement_parameter_custodians_precall(wrapper): + for custodian, ward, postcall in wrapper.custodians_and_wards: + if not postcall: + _add_ward(wrapper.before_call, + _get_custodian_or_ward(wrapper, custodian), + _get_custodian_or_ward(wrapper, ward)) + + +def implement_parameter_custodians_postcall(wrapper): + for custodian, ward, postcall in wrapper.custodians_and_wards: + if postcall: + _add_ward(wrapper.after_call, + _get_custodian_or_ward(wrapper, custodian), + _get_custodian_or_ward(wrapper, ward)) diff --git a/pybindgen/cppmethod.py b/pybindgen/cppmethod.py index cbf48d1..ea57509 100644 --- a/pybindgen/cppmethod.py +++ b/pybindgen/cppmethod.py @@ -123,6 +123,24 @@ class CppMethod(ForwardWrapperBase): assert isinstance(t, CppException) self.throw = list(throw) + self.custodians_and_wards = [] # list of (custodian, ward, postcall) + cppclass_typehandlers.scan_custodians_and_wards(self) + + + def add_custodian_and_ward(self, custodian, ward, postcall=None): + """ TODO: document this """ + if custodian == -1 or ward == -1: + if postcall is None: + postcall = True + if not postcall: + raise TypeConfigurationError("custodian/ward policy must be postcall " + "when a return value is involved") + else: + if postcall is None: + postcall = False + self.custodians_and_wards.append((custodian, ward, postcall)) + + def set_helper_class(self, helper_class): "Set the C++ helper class, which is used for overriding virtual methods" self._helper_class = helper_class @@ -227,11 +245,14 @@ class CppMethod(ForwardWrapperBase): self.before_call.unindent() self.before_call.write_code('}') + def _before_call_hook(self): + "hook that post-processes parameters and check for custodian= CppClass parameters" + cppclass_typehandlers.implement_parameter_custodians_precall(self) def _before_return_hook(self): """hook that post-processes parameters and check for custodian= CppClass parameters""" - cppclass_typehandlers.implement_parameter_custodians(self) + cppclass_typehandlers.implement_parameter_custodians_postcall(self) def _get_pystruct(self): # When a method is used in the context of a helper class, we @@ -464,6 +485,24 @@ class CppConstructor(ForwardWrapperBase): assert isinstance(t, CppException) self.throw = list(throw) + self.custodians_and_wards = [] # list of (custodian, ward, postcall) + cppclass_typehandlers.scan_custodians_and_wards(self) + + + def add_custodian_and_ward(self, custodian, ward, postcall=None): + """ TODO: document this """ + if custodian == -1 or ward == -1: + if postcall is None: + postcall = True + if not postcall: + raise TypeConfigurationError("custodian/ward policy must be postcall " + "when a return value is involved") + else: + if postcall is None: + postcall = False + self.custodians_and_wards.append((custodian, ward, postcall)) + + def clone(self): """Creates a semi-deep copy of this constructor wrapper. The returned constructor wrapper clone contains copies of all parameters, so @@ -539,10 +578,13 @@ class CppConstructor(ForwardWrapperBase): self.before_call.unindent() self.before_call.write_code('}') + def _before_call_hook(self): + "hook that post-processes parameters and check for custodian= CppClass parameters" + cppclass_typehandlers.implement_parameter_custodians_precall(self) def _before_return_hook(self): "hook that post-processes parameters and check for custodian= CppClass parameters" - cppclass_typehandlers.implement_parameter_custodians(self) + cppclass_typehandlers.implement_parameter_custodians_postcall(self) def generate(self, code_sink, wrapper_name=None, extra_wrapper_params=()): """ diff --git a/pybindgen/function.py b/pybindgen/function.py index 0925089..a633360 100644 --- a/pybindgen/function.py +++ b/pybindgen/function.py @@ -82,6 +82,9 @@ class Function(ForwardWrapperBase): for t in throw: assert isinstance(t, CppException) self.throw = list(throw) + self.custodians_and_wards = [] # list of (custodian, ward, postcall) + cppclass_typehandlers.scan_custodians_and_wards(self) + def clone(self): """Creates a semi-deep copy of this function wrapper. The returned @@ -95,8 +98,24 @@ class Function(ForwardWrapperBase): func._module = self._module func.wrapper_base_name = self.wrapper_base_name func.wrapper_actual_name = self.wrapper_actual_name + func.throw = list(self.throw) + func.custodians_and_wards = list(self.custodians_and_wards) + return func + def add_custodian_and_ward(self, custodian, ward, postcall=None): + """ TODO: document this """ + if custodian == -1 or ward == -1: + if postcall is None: + postcall = True + if not postcall: + raise TypeConfigurationError("custodian/ward policy must be postcall " + "when a return value is involved") + else: + if postcall is None: + postcall = False + self.custodians_and_wards.append((custodian, ward, postcall)) + def get_module(self): """Get the Module object this function belongs to""" return self._module @@ -151,9 +170,13 @@ class Function(ForwardWrapperBase): self.before_call.unindent() self.before_call.write_code('}') + def _before_call_hook(self): + "hook that post-processes parameters and check for custodian= CppClass parameters" + cppclass_typehandlers.implement_parameter_custodians_precall(self) + def _before_return_hook(self): "hook that post-processes parameters and check for custodian= CppClass parameters" - cppclass_typehandlers.implement_parameter_custodians(self) + cppclass_typehandlers.implement_parameter_custodians_postcall(self) def generate(self, code_sink, wrapper_name=None, extra_wrapper_params=()): """ diff --git a/pybindgen/typehandlers/base.py b/pybindgen/typehandlers/base.py index 2952be9..ea70c42 100644 --- a/pybindgen/typehandlers/base.py +++ b/pybindgen/typehandlers/base.py @@ -800,6 +800,14 @@ class ForwardWrapperBase(object): """ raise NotImplementedError + def _before_call_hook(self): + """ + Optional hook that lets subclasses add code after all + parameters are parsed, but before the C function/method call. + Subclasses may add code to self.before_call. + """ + pass + def _before_return_hook(self): """ Optional hook that lets subclasses add code after all @@ -855,6 +863,8 @@ class ForwardWrapperBase(object): msg = "Deprecated" self.before_call.write_error_check( 'PyErr_Warn(PyExc_DeprecationWarning, (char *) "%s")' % msg) + self._before_call_hook() + if self.unblock_threads: self.before_call.write_code( "\nif (PyEval_ThreadsInitialized ())\n"