From a6287ccc4b32c6662431b0d201cea4a01f09eecb Mon Sep 17 00:00:00 2001 From: "Gustavo J. A. M. Carneiro" Date: Sun, 27 Dec 2009 23:24:37 +0000 Subject: [PATCH] Align virtual method handling code with other tools: to implement virtual method foo, now the user defines a method foo in Python, not _foo. Option pybindgen.settings.deprecated_virtuals added for backward compatibility. --- benchmarks/bench.py | 21 ++-------- benchmarks/testapi-pybindgen.py | 4 +- pybindgen/cppclass.py | 12 +++++- pybindgen/cppmethod.py | 74 ++++++++++++++++++++++++++------- pybindgen/settings.py | 23 ++++++++++ tests/foomodulegen_common.py | 1 + tests/footest.py | 40 +++++++++--------- tests/test-generation.py | 3 ++ 8 files changed, 121 insertions(+), 57 deletions(-) diff --git a/benchmarks/bench.py b/benchmarks/bench.py index 5f8f530..464d9b0 100644 --- a/benchmarks/bench.py +++ b/benchmarks/bench.py @@ -79,24 +79,9 @@ def bench(mod, dom, elem): tst.setAttribute("time", repr(Timer(bench).timeit(TIMES))) print "%s (%s): %s" % (tst.tagName, tst.getAttribute('description'), tst.getAttribute('time')) - if mod is testapi_pybindgen: - class M(mod.Multiplier): - def _Multiply(self, value): - return super(M, self)._Multiply(value) - elif mod is testapi_boost: - class M(mod.Multiplier): - def Multiply(self, value): - return super(M, self).Multiply(value) - elif mod is testapi_swig: - class M(mod.Multiplier): - def Multiply(self, value): - return super(M, self).Multiply(value) - elif mod is testapi_sip: - class M(mod.Multiplier): - def Multiply(self, value): - return super(M, self).Multiply(value) - else: - raise NotImplementedError + class M(mod.Multiplier): + def Multiply(self, value): + return super(M, self).Multiply(value) obj = M(2.0) def bench(): return obj.Multiply(5.0) diff --git a/benchmarks/testapi-pybindgen.py b/benchmarks/testapi-pybindgen.py index b8e5ee1..f3b63ea 100644 --- a/benchmarks/testapi-pybindgen.py +++ b/benchmarks/testapi-pybindgen.py @@ -3,10 +3,12 @@ import sys from pybindgen import Module, retval, param, FileCodeSink - +import pybindgen.settings def my_module_gen(out_file): + pybindgen.settings.deprecated_virtuals = False + mod = Module('testapi_pybindgen') mod.add_include('"testapi.h"') diff --git a/pybindgen/cppclass.py b/pybindgen/cppclass.py index e3e7140..ade0f0c 100644 --- a/pybindgen/cppclass.py +++ b/pybindgen/cppclass.py @@ -204,7 +204,11 @@ class CppHelperClass(object): else: self.virtual_methods.append(method) if not method.is_pure_virtual: - if method.visibility in ['public', 'protected']: + if settings._get_deprecated_virtuals(): + vis = ['public', 'protected'] + else: + vis = ['protected'] + if method.visibility in vis: parent_caller = CppVirtualMethodParentCaller(method) #parent_caller.class_ = method.class_ parent_caller.helper_class = self @@ -393,7 +397,11 @@ void set_pyobj(PyObject *pyobj) (code_sink,), {}, parent_caller) except utils.SkipWrapper: continue - method_defs.append(parent_caller.get_py_method_def('_' + name)) + if settings._get_deprecated_virtuals(): + parent_caller_name = '_'+name + else: + parent_caller_name = name + method_defs.append(parent_caller.get_py_method_def(parent_caller_name)) ## write the virtual proxies for virtual_proxy in self.virtual_proxies: diff --git a/pybindgen/cppmethod.py b/pybindgen/cppmethod.py index 896d5ac..e37d3aa 100644 --- a/pybindgen/cppmethod.py +++ b/pybindgen/cppmethod.py @@ -238,29 +238,55 @@ class CppMethod(ForwardWrapperBase): template_params = '< %s >' % ', '.join(self.template_parameters) else: template_params = '' + + + if self.return_value.ctype == 'void': + retval_assign = '' + else: + if self.return_value.REQUIRES_ASSIGNMENT_CONSTRUCTOR: + retval_assign = '%s retval = ' % (self.return_value.ctype,) + else: + retval_assign = 'retval = ' + + if class_.helper_class is not None and self.is_virtual and not self.is_pure_virtual\ + and not settings._get_deprecated_virtuals(): + helper = self.before_call.declare_variable(type_="%s *" % class_.helper_class.name, + name="helper_class", + initializer=( + "dynamic_cast<%s*> (self->obj)" % class_.helper_class.name)) + else: + helper = None + if self.is_static: method = '%s::%s%s' % (class_.full_name, self.method_name, template_params) else: method = 'self->obj->%s%s' % (self.method_name, template_params) - if self.throw: self.before_call.write_code('try\n{') self.before_call.indent() - if self.return_value.ctype == 'void': - self.before_call.write_code( - '%s(%s);' % - (method, ", ".join(self.call_params))) + if self.is_static: + self.before_call.write_code(retval_assign + ( + '%s::%s%s(%s);' % (class_.full_name, + self.method_name, template_params, + ", ".join(self.call_params)))) else: - if self.return_value.REQUIRES_ASSIGNMENT_CONSTRUCTOR: - self.before_call.write_code( - '%s retval = %s(%s);' % - (self.return_value.ctype, method, ", ".join(self.call_params))) + if helper is None: + self.before_call.write_code(retval_assign + ( + 'self->obj->%s%s(%s);' % (self.method_name, template_params, + ", ".join(self.call_params)))) else: - self.before_call.write_code( - 'retval = %s(%s);' % - (method, ", ".join(self.call_params))) + self.before_call.write_code(retval_assign + ( + '(%s == NULL)? (self->obj->%s%s(%s)) : (self->obj->%s::%s%s(%s));' + % (helper, + + self.method_name, template_params, + ", ".join(self.call_params), + + class_.full_name, self.method_name, template_params, + ", ".join(self.call_params) + ))) if self.throw: for exc in self.throw: @@ -840,7 +866,16 @@ class CppVirtualMethodParentCaller(CppMethod): def generate_call(self, class_=None): "virtual method implementation; do not call" class_ = self.class_ - method = 'reinterpret_cast< %s* >(self->obj)->%s__parent_caller' % (self._helper_class.name, self.method_name) + helper = self.before_call.declare_variable( + type_=('%s*' % self._helper_class.name), + name='helper', + initializer=("dynamic_cast< %s* >(self->obj)" % self._helper_class.name)) + method = '%s->%s__parent_caller' % (helper, self.method_name) + self.before_call.write_error_check( + "%s == NULL" % helper, + 'PyErr_SetString(PyExc_TypeError, "Method %s of class %s is protected and can only be called by a subclass");' + % (self.method_name, self.class_.name)) + if self.return_value.ctype == 'void': self.before_call.write_code( '%s(%s);' % @@ -919,7 +954,10 @@ class CppVirtualMethodProxy(ReverseWrapperBase): def generate_python_call(self): """code to call the python method""" - params = ['m_pyself', '(char *) "_%s"' % self.method_name] + if settings._get_deprecated_virtuals(): + params = ['m_pyself', '(char *) "_%s"' % self.method_name] + else: + params = ['m_pyself', '(char *) "%s"' % self.method_name] build_params = self.build_params.get_parameters() if build_params[0][0] == '"': build_params[0] = '(char *) ' + build_params[0] @@ -953,8 +991,12 @@ class CppVirtualMethodProxy(ReverseWrapperBase): ## just chain to parent class and don't do anything else call_params = ', '.join([param.name for param in self.parameters]) py_method = self.declarations.declare_variable('PyObject*', 'py_method') - self.before_call.write_code('%s = PyObject_GetAttrString(m_pyself, (char *) "_%s"); PyErr_Clear();' - % (py_method, self.method_name)) + if settings._get_deprecated_virtuals(): + self.before_call.write_code('%s = PyObject_GetAttrString(m_pyself, (char *) "_%s"); PyErr_Clear();' + % (py_method, self.method_name)) + else: + self.before_call.write_code('%s = PyObject_GetAttrString(m_pyself, (char *) "%s"); PyErr_Clear();' + % (py_method, self.method_name)) self.before_call.add_cleanup_code('Py_XDECREF(%s);' % py_method) self.before_call.write_code( diff --git a/pybindgen/settings.py b/pybindgen/settings.py index cae79d2..5f3f2f7 100644 --- a/pybindgen/settings.py +++ b/pybindgen/settings.py @@ -53,6 +53,29 @@ wrapper registries. A wrapper registry ensures that at most one python wrapper exists for each C/C++ object. """ +deprecated_virtuals = None +""" +Prior to PyBindGen version 0.14, the code generated to handle C++ +virtual methods required Python user code to define a _foo method in +order to implement the virtual method foo. Since 0.14, PyBindGen +changed so that virtual method foo is implemented in Python by +defining a method foo, i.e. no underscore prefix is needed anymore. +Setting deprecated_virtuals to True will force the old virtual method +behaviour. But this is really deprecated; newer code should set +deprecated_virtuals to False. +""" + +def _get_deprecated_virtuals(): + if deprecated_virtuals is None: + import warnings + warnings.warn("The option pybindgen.settings.deprecated_virtuals has not been set." + " I am going to assume the value of True, to preserve backward" + " compatibility, but the default value will change in the future," + " and the option will eventually disappear.", + DeprecationWarning) + return True + return deprecated_virtuals + class ErrorHandler(object): def handle_error(self, wrapper, exception, traceback_): diff --git a/tests/foomodulegen_common.py b/tests/foomodulegen_common.py index 075dbdf..353c8b9 100644 --- a/tests/foomodulegen_common.py +++ b/tests/foomodulegen_common.py @@ -53,6 +53,7 @@ del transf def customize_module(module): pybindgen.settings.wrapper_registry = pybindgen.settings.StdMapWrapperRegistry + pybindgen.settings.deprecated_virtuals = False wrapper_body = ''' static PyObject * diff --git a/tests/footest.py b/tests/footest.py index f7de730..53a8ddd 100644 --- a/tests/footest.py +++ b/tests/footest.py @@ -199,7 +199,7 @@ class TestFoo(unittest.TestCase): def test_virtual_subclass(self): class Test(foo.SomeObject): - def _get_prefix(self): + def get_prefix(self): return "yyy" t = Test("xxx") @@ -207,8 +207,8 @@ class TestFoo(unittest.TestCase): def test_virtual_with_chaining_to_parent_class(self): class Test(foo.SomeObject): - def _get_prefix(self): - prefix = super(Test, self)._get_prefix() + def get_prefix(self): + prefix = super(Test, self).get_prefix() return prefix + "yyy" t = Test("xxx") @@ -262,8 +262,8 @@ class TestFoo(unittest.TestCase): def __init__(self, prefix, extra_prefix): super(Test, self).__init__(prefix) self.extra_prefix = extra_prefix - def _get_prefix(self): - prefix = super(Test, self)._get_prefix() + def get_prefix(self): + prefix = super(Test, self).get_prefix() return prefix + self.extra_prefix while gc.collect(): pass @@ -523,8 +523,8 @@ class TestFoo(unittest.TestCase): def __init__(self, prefix, extra_prefix): super(Test, self).__init__(prefix) self.extra_prefix = extra_prefix - def _get_prefix_with_foo_value(self, fooval): - prefix = super(Test, self)._get_prefix_with_foo_value(fooval) + def get_prefix_with_foo_value(self, fooval): + prefix = super(Test, self).get_prefix_with_foo_value(fooval) return prefix + self.extra_prefix + fooval.get_datum() t = Test("123", "456") @@ -537,8 +537,8 @@ class TestFoo(unittest.TestCase): def __init__(self, prefix, extra_prefix): super(Test, self).__init__(prefix) self.extra_prefix = extra_prefix - def _get_prefix_with_foo_ref(self, fooval): - prefix = super(Test, self)._get_prefix_with_foo_ref(fooval) + def get_prefix_with_foo_ref(self, fooval): + prefix = super(Test, self).get_prefix_with_foo_ref(fooval) return prefix + self.extra_prefix + fooval.get_datum() t = Test("123", "456") @@ -552,8 +552,8 @@ class TestFoo(unittest.TestCase): def __init__(self, prefix, extra_prefix): super(Test, self).__init__(prefix) self.extra_prefix = extra_prefix - def _get_prefix_with_foo_ptr(self, fooval): - prefix = super(Test, self)._get_prefix_with_foo_ptr(fooval) + def get_prefix_with_foo_ptr(self, fooval): + prefix = super(Test, self).get_prefix_with_foo_ptr(fooval) return prefix + self.extra_prefix + fooval.get_datum() t = Test("123", "456") @@ -632,7 +632,7 @@ class TestFoo(unittest.TestCase): def test_private_virtual(self): class Class(foo.AbstractBaseClass2): - def _private_virtual(self, x): + def private_virtual(self, x): return x*x c = Class() x = c.invoke_private_virtual(2) @@ -640,10 +640,10 @@ class TestFoo(unittest.TestCase): def test_protected_virtual(self): class Class(foo.AbstractBaseClass2): - def _private_virtual(self, x): + def private_virtual(self, x): return x*x - def _protected_virtual(self, x): - y = super(Class, self)._protected_virtual(x) + def protected_virtual(self, x): + y = super(Class, self).protected_virtual(x) return y*y c = Class() x = c.invoke_protected_virtual(2) @@ -651,7 +651,7 @@ class TestFoo(unittest.TestCase): def test_protected_pure_virtual(self): class Class(foo.AbstractBaseClass2): - def _protected_pure_virtual(self, x): + def protected_pure_virtual(self, x): return x*x+1 c = Class() x = c.invoke_protected_pure_virtual(2) @@ -662,7 +662,7 @@ class TestFoo(unittest.TestCase): def __init__(self, y): super(Test, self).__init__("foo") self.y = y - def _get_int(self, x): + def get_int(self, x): return getattr(self, 'y', 0) + x while gc.collect(): @@ -851,7 +851,7 @@ class TestFoo(unittest.TestCase): super(MyTestContainer, self).__init__() self.list_that_was_set = None - def _get_simple_list(self): + def get_simple_list(self): l = [] for i in range(5): simple = foo.simple_struct_t() @@ -860,7 +860,7 @@ class TestFoo(unittest.TestCase): #container = foo.SimpleStructList(l) return l - def _set_simple_list(self, container): + def set_simple_list(self, container): self.list_that_was_set = container return sum([s.xpto for s in container]) @@ -1134,7 +1134,7 @@ class TestFoo(unittest.TestCase): def test_virtual_method_reference_parameter(self): class MyReferenceManipulator(foo.ReferenceManipulator): - def _do_manipulate_object(self, obj): + def do_manipulate_object(self, obj): obj.SetValue(12345) manip = MyReferenceManipulator() retval = manip.manipulate_object() diff --git a/tests/test-generation.py b/tests/test-generation.py index 83b0029..0501059 100755 --- a/tests/test-generation.py +++ b/tests/test-generation.py @@ -11,6 +11,9 @@ from pybindgen.module import Module from pybindgen import cppclass from pybindgen.typehandlers.base import NotSupportedError +import pybindgen.settings +pybindgen.settings.deprecated_virtuals = False + import re stdint_rx = re.compile(".*int\\d+_t.*")