From 2cbd986fbca2019b178e934fa456ecb5a2d78bd8 Mon Sep 17 00:00:00 2001 From: "Gustavo J. A. M. Carneiro" Date: Wed, 23 Feb 2011 15:16:27 +0000 Subject: [PATCH 01/20] Add a boost::shared_ptr example --- examples/shared_ptr/c.cc | 8 +++++ examples/shared_ptr/c.h | 13 ++++++++ examples/shared_ptr/c_test.py | 9 ++++++ examples/shared_ptr/modulegen.py | 53 ++++++++++++++++++++++++++++++++ examples/shared_ptr/wscript | 22 +++++++++++++ examples/wscript | 7 +++++ wscript | 3 ++ 7 files changed, 115 insertions(+) create mode 100644 examples/shared_ptr/c.cc create mode 100644 examples/shared_ptr/c.h create mode 100644 examples/shared_ptr/c_test.py create mode 100644 examples/shared_ptr/modulegen.py create mode 100644 examples/shared_ptr/wscript diff --git a/examples/shared_ptr/c.cc b/examples/shared_ptr/c.cc new file mode 100644 index 0000000..e419740 --- /dev/null +++ b/examples/shared_ptr/c.cc @@ -0,0 +1,8 @@ +#include "c.h" + +TestClass::Ptr someFct() +{ + TestClass::Ptr p(new TestClass); + return p; +} + diff --git a/examples/shared_ptr/c.h b/examples/shared_ptr/c.h new file mode 100644 index 0000000..84bca49 --- /dev/null +++ b/examples/shared_ptr/c.h @@ -0,0 +1,13 @@ +// -*- C++ -*- + +#include + +class TestClass { + public: + typedef boost::shared_ptr< TestClass > Ptr; + public: +}; + + +TestClass::Ptr someFct(); + diff --git a/examples/shared_ptr/c_test.py b/examples/shared_ptr/c_test.py new file mode 100644 index 0000000..2dda1d3 --- /dev/null +++ b/examples/shared_ptr/c_test.py @@ -0,0 +1,9 @@ +import sys +sys.path.insert(0, "../../build/default/examples/callback") +import c + +def visitor(value): + print value + +c.visit(visitor) + diff --git a/examples/shared_ptr/modulegen.py b/examples/shared_ptr/modulegen.py new file mode 100644 index 0000000..90b1b93 --- /dev/null +++ b/examples/shared_ptr/modulegen.py @@ -0,0 +1,53 @@ +#! /usr/bin/env python + +import sys + +import pybindgen +from pybindgen import ReturnValue, Parameter, Module, Function, FileCodeSink +from pybindgen import CppMethod, CppConstructor, CppClass, Enum +from pybindgen.typehandlers.base import ForwardWrapperBase +from pybindgen.typehandlers import base as typehandlers + +class SharedPtrTransformation(typehandlers.TypeTransformation): + def get_untransformed_name(self, name): + if name == 'TestClass::Ptr': + return 'TestClass *' + return name + + def create_type_handler(self, type_handler, *args, **kwargs): + if issubclass(type_handler, Parameter): + kwargs['transfer_ownership'] = False + elif issubclass(type_handler, ReturnValue): + kwargs['caller_owns_return'] = False + else: + raise AssertionError + handler = type_handler(*args, **kwargs) + handler.set_transformation(self, self.get_untransformed_name(args[0])) + return handler + + def untransform(self, type_handler, declarations, code_block, expression): + return '(%s).get()' % (expression,) + + def transform(self, type_handler, declarations, code_block, expression): + assert type_handler.untransformed_ctype[-1] == '*' # make sure it's a pointer + return 'TestClass::Ptr (expression)' + +transf = SharedPtrTransformation() +typehandlers.return_type_matcher.register_transformation(transf) +typehandlers.param_type_matcher.register_transformation(transf) +del transf + + +def my_module_gen(out_file): + + mod = Module('c') + mod.add_include('"c.h"') + + mod.add_class('TestClass') + + mod.add_function("someFct", 'TestClass::Ptr', []) + + mod.generate(FileCodeSink(out_file)) + +if __name__ == '__main__': + my_module_gen(sys.stdout) diff --git a/examples/shared_ptr/wscript b/examples/shared_ptr/wscript new file mode 100644 index 0000000..287103c --- /dev/null +++ b/examples/shared_ptr/wscript @@ -0,0 +1,22 @@ +## -*- python -*- + + +def build(bld): + + gen = bld.new_task_gen( + features='command', + source='modulegen.py', + target='cmodule.cc', + command='${PYTHON} ${SRC[0]} > ${TGT[0]}') + + if bld.env['CXX']: + obj = bld.new_task_gen('cxx', 'shlib', 'pyext') + obj.source = [ + 'c.cc', + 'cmodule.cc' + ] + obj.target = 'c' + obj.install_path = None # do not install + obj.includes = '.' + obj.uselib = 'BOOST' + diff --git a/examples/wscript b/examples/wscript index 31b2a52..4b4c738 100644 --- a/examples/wscript +++ b/examples/wscript @@ -1,6 +1,13 @@ ## -*- python -*- +def set_options(opt): + opt.tool_options('boost') + def build(bld): bld.add_subdirs('a b c d e f g h') bld.add_subdirs('callback') + if bld.env['HAVE_BOOST']: + bld.add_subdirs('shared_ptr') +def configure(conf): + conf.env['HAVE_BOOST'] = conf.check_boost() diff --git a/wscript b/wscript index eaac5ea..de321ef 100644 --- a/wscript +++ b/wscript @@ -202,6 +202,8 @@ def set_options(opt): opt.tool_options('compiler_cc') opt.tool_options('compiler_cxx') opt.tool_options('cflags') + opt.sub_options('examples') + optgrp = opt.add_option_group("PyBindGen Options") @@ -291,6 +293,7 @@ def configure(conf): conf.env.append_value('CPPPATH', os.path.join(conf.curdir, 'include')) conf.sub_config('benchmarks') + conf.sub_config('examples') def build(bld): From a638217c9f9b05e477e95a88a1f92f30f33a00bf Mon Sep 17 00:00:00 2001 From: "Gustavo J. A. M. Carneiro" Date: Sat, 12 Mar 2011 18:33:42 +0000 Subject: [PATCH 02/20] import_from_module bug fixes --- pybindgen/cppclass.py | 29 +++++++++++++---------------- pybindgen/wrapper_registry.py | 33 ++++++++++++++++++++++++++++----- 2 files changed, 41 insertions(+), 21 deletions(-) diff --git a/pybindgen/cppclass.py b/pybindgen/cppclass.py index c6b1560..3466058 100644 --- a/pybindgen/cppclass.py +++ b/pybindgen/cppclass.py @@ -1660,7 +1660,7 @@ typedef struct { self.container_traits.generate_forward_declarations(code_sink, module) if self.parent is None: - self.wrapper_registry.generate_forward_declarations(code_sink, module) + self.wrapper_registry.generate_forward_declarations(code_sink, module, self.import_from_module) def get_python_name(self): if self.template_parameters: @@ -1687,23 +1687,16 @@ typedef struct { module.after_init.write_code("PyObject *module = PyImport_ImportModule(\"%s\");" % module_name) module.after_init.write_code( "if (module == NULL) {\n" - " _%s = NULL;\n" - " PyErr_Print();\n" - " if (PyErr_WarnEx(PyExc_RuntimeWarning, \"Unable to import type '%s' from module '%s';\", 1))\n" - " return;\n" - "} else {\n" % (self.pytypestruct, type_name, module_name)) - module.after_init.write_code(" _%s = (PyTypeObject*) PyObject_GetAttrString(module, \"%s\");\n" - "}" - % (self.pytypestruct, type_name)) - module.after_init.write_code("PyErr_Clear();") - module.after_init.unindent(); module.after_init.write_code("}") + " return;\n" + "}") + + module.after_init.write_code("_%s = (PyTypeObject*) PyObject_GetAttrString(module, \"%s\");\n" + % (self.pytypestruct, self.get_python_name())) + module.after_init.write_code("if (PyErr_Occurred()) PyErr_Clear();") if self.typeid_map_name is not None: code_sink.writeln("pybindgen::TypeMap *_%s;" % self.typeid_map_name) module.after_init.write_code("/* Import the %r class type map from module %r */" % (self.full_name, self.import_from_module)) - module.after_init.write_code("{"); module.after_init.indent() - module.after_init.write_code("PyObject *module = PyImport_ImportModule(\"%s\");" % module_name) - module.after_init.write_code("if (module == NULL) PyErr_Print();") module.after_init.write_code("PyObject *_cobj = PyObject_GetAttrString(module, \"_%s\");" % (self.typeid_map_name)) module.after_init.write_code("if (_cobj == NULL) {\n" @@ -1713,8 +1706,12 @@ typedef struct { " _%s = reinterpret_cast (PyCObject_AsVoidPtr (_cobj));\n" " Py_DECREF(_cobj);\n" "}" - % (self.typeid_map_name, self.typeid_map_name)) - module.after_init.unindent(); module.after_init.write_code("}") + % (self.typeid_map_name, self.typeid_map_name)) + + if self.parent is None: + self.wrapper_registry.generate_import(code_sink, module.after_init, "module") + + module.after_init.unindent(); module.after_init.write_code("}") if self.helper_class is not None: self.helper_class.generate(code_sink) diff --git a/pybindgen/wrapper_registry.py b/pybindgen/wrapper_registry.py index 7af24f7..b99995a 100644 --- a/pybindgen/wrapper_registry.py +++ b/pybindgen/wrapper_registry.py @@ -17,7 +17,7 @@ class WrapperRegistry(object): def generate_forward_declarations(self, code_sink, module): raise NotImplementedError - def generate(self, code_sink, module): + def generate(self, code_sink, module, import_from_module): raise NotImplementedError def write_register_new_wrapper(self, code_block, wrapper_lvalue, object_rvalue): @@ -40,11 +40,13 @@ class NullWrapperRegistry(WrapperRegistry): def __init__(self, base_name): super(NullWrapperRegistry, self).__init__(base_name) - def generate_forward_declarations(self, code_sink, module): + def generate_forward_declarations(self, code_sink, module, import_from_module): pass def generate(self, code_sink, module): pass + def generate_import(self, code_sink, module, import_from_module): + pass def write_register_new_wrapper(self, code_block, wrapper_lvalue, object_rvalue): pass @@ -63,19 +65,40 @@ class StdMapWrapperRegistry(WrapperRegistry): not compile. """ + def __init__(self, base_name): super(StdMapWrapperRegistry, self).__init__(base_name) self.map_name = "%s_wrapper_registry" % base_name - def generate_forward_declarations(self, code_sink, module): + def generate_forward_declarations(self, code_sink, module, import_from_module): module.add_include("") module.add_include("") #code_sink.writeln("#include ") #code_sink.writeln("#include ") - code_sink.writeln("extern std::map %s;" % self.map_name) + if import_from_module: + code_sink.writeln("extern std::map *_%s;" % self.map_name) + code_sink.writeln("#define %s (*_%s)" % (self.map_name, self.map_name)) + else: + code_sink.writeln("extern std::map %s;" % self.map_name) - def generate(self, code_sink, dummy_module): + def generate(self, code_sink, module): code_sink.writeln("std::map %s;" % self.map_name) + # register the map in the module namespace + module.after_init.write_code("PyModule_AddObject(m, (char *) \"_%s\", PyCObject_FromVoidPtr(&%s, NULL));" + % (self.map_name, self.map_name)) + + def generate_import(self, code_sink, code_block, module_pyobj_var): + code_sink.writeln("std::map *_%s;" % self.map_name) + code_block.write_code("PyObject *_cobj = PyObject_GetAttrString(%s, \"_%s\");" + % (module_pyobj_var, self.map_name)) + code_block.write_code("if (_cobj == NULL) {\n" + " _%(MAP)s = NULL;\n" + " PyErr_Print();\n" + "} else {\n" + " _%(MAP)s = reinterpret_cast< std::map *> (PyCObject_AsVoidPtr (_cobj));\n" + " Py_DECREF(_cobj);\n" + "}" + % dict(MAP=self.map_name)) def write_register_new_wrapper(self, code_block, wrapper_lvalue, object_rvalue): code_block.write_code("%s[(void *) %s] = (PyObject *) %s;" % (self.map_name, object_rvalue, wrapper_lvalue)) From 2c53d311f1900189f2881e61c0f98db64f1db83f Mon Sep 17 00:00:00 2001 From: "Gustavo J. A. M. Carneiro" Date: Sun, 20 Mar 2011 15:15:47 +0000 Subject: [PATCH 03/20] Fix submodule init function name generation to avoid name clashes --- pybindgen/module.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/pybindgen/module.py b/pybindgen/module.py index fbf9a07..7592006 100644 --- a/pybindgen/module.py +++ b/pybindgen/module.py @@ -315,11 +315,10 @@ class ModuleBase(dict): if self.parent is None: self.prefix = self.name.replace('.', '_') + self.init_function_name = "init%s" % (self.name.split('.')[-1],) else: self.prefix = self.parent.prefix + "_" + self.name - - self.init_function_name = "init%s" % (self.name.split('.')[-1],) - + self.init_function_name = "init%s" % (self.prefix,) name = property(get_name, set_name) From 9e883068ad7a3d8e5c054cfae1311339577b3f8e Mon Sep 17 00:00:00 2001 From: "Gustavo J. A. M. Carneiro" Date: Tue, 22 Mar 2011 16:28:52 +0000 Subject: [PATCH 04/20] Remove the boost::shared_ptr example, it is broken anyhow --- examples/shared_ptr/c.cc | 8 ----- examples/shared_ptr/c.h | 13 -------- examples/shared_ptr/c_test.py | 9 ------ examples/shared_ptr/modulegen.py | 53 -------------------------------- examples/shared_ptr/wscript | 22 ------------- examples/wscript | 9 +++--- 6 files changed, 5 insertions(+), 109 deletions(-) delete mode 100644 examples/shared_ptr/c.cc delete mode 100644 examples/shared_ptr/c.h delete mode 100644 examples/shared_ptr/c_test.py delete mode 100644 examples/shared_ptr/modulegen.py delete mode 100644 examples/shared_ptr/wscript diff --git a/examples/shared_ptr/c.cc b/examples/shared_ptr/c.cc deleted file mode 100644 index e419740..0000000 --- a/examples/shared_ptr/c.cc +++ /dev/null @@ -1,8 +0,0 @@ -#include "c.h" - -TestClass::Ptr someFct() -{ - TestClass::Ptr p(new TestClass); - return p; -} - diff --git a/examples/shared_ptr/c.h b/examples/shared_ptr/c.h deleted file mode 100644 index 84bca49..0000000 --- a/examples/shared_ptr/c.h +++ /dev/null @@ -1,13 +0,0 @@ -// -*- C++ -*- - -#include - -class TestClass { - public: - typedef boost::shared_ptr< TestClass > Ptr; - public: -}; - - -TestClass::Ptr someFct(); - diff --git a/examples/shared_ptr/c_test.py b/examples/shared_ptr/c_test.py deleted file mode 100644 index 2dda1d3..0000000 --- a/examples/shared_ptr/c_test.py +++ /dev/null @@ -1,9 +0,0 @@ -import sys -sys.path.insert(0, "../../build/default/examples/callback") -import c - -def visitor(value): - print value - -c.visit(visitor) - diff --git a/examples/shared_ptr/modulegen.py b/examples/shared_ptr/modulegen.py deleted file mode 100644 index 90b1b93..0000000 --- a/examples/shared_ptr/modulegen.py +++ /dev/null @@ -1,53 +0,0 @@ -#! /usr/bin/env python - -import sys - -import pybindgen -from pybindgen import ReturnValue, Parameter, Module, Function, FileCodeSink -from pybindgen import CppMethod, CppConstructor, CppClass, Enum -from pybindgen.typehandlers.base import ForwardWrapperBase -from pybindgen.typehandlers import base as typehandlers - -class SharedPtrTransformation(typehandlers.TypeTransformation): - def get_untransformed_name(self, name): - if name == 'TestClass::Ptr': - return 'TestClass *' - return name - - def create_type_handler(self, type_handler, *args, **kwargs): - if issubclass(type_handler, Parameter): - kwargs['transfer_ownership'] = False - elif issubclass(type_handler, ReturnValue): - kwargs['caller_owns_return'] = False - else: - raise AssertionError - handler = type_handler(*args, **kwargs) - handler.set_transformation(self, self.get_untransformed_name(args[0])) - return handler - - def untransform(self, type_handler, declarations, code_block, expression): - return '(%s).get()' % (expression,) - - def transform(self, type_handler, declarations, code_block, expression): - assert type_handler.untransformed_ctype[-1] == '*' # make sure it's a pointer - return 'TestClass::Ptr (expression)' - -transf = SharedPtrTransformation() -typehandlers.return_type_matcher.register_transformation(transf) -typehandlers.param_type_matcher.register_transformation(transf) -del transf - - -def my_module_gen(out_file): - - mod = Module('c') - mod.add_include('"c.h"') - - mod.add_class('TestClass') - - mod.add_function("someFct", 'TestClass::Ptr', []) - - mod.generate(FileCodeSink(out_file)) - -if __name__ == '__main__': - my_module_gen(sys.stdout) diff --git a/examples/shared_ptr/wscript b/examples/shared_ptr/wscript deleted file mode 100644 index 287103c..0000000 --- a/examples/shared_ptr/wscript +++ /dev/null @@ -1,22 +0,0 @@ -## -*- python -*- - - -def build(bld): - - gen = bld.new_task_gen( - features='command', - source='modulegen.py', - target='cmodule.cc', - command='${PYTHON} ${SRC[0]} > ${TGT[0]}') - - if bld.env['CXX']: - obj = bld.new_task_gen('cxx', 'shlib', 'pyext') - obj.source = [ - 'c.cc', - 'cmodule.cc' - ] - obj.target = 'c' - obj.install_path = None # do not install - obj.includes = '.' - obj.uselib = 'BOOST' - diff --git a/examples/wscript b/examples/wscript index 4b4c738..5b42dda 100644 --- a/examples/wscript +++ b/examples/wscript @@ -1,13 +1,14 @@ ## -*- python -*- def set_options(opt): - opt.tool_options('boost') + pass#opt.tool_options('boost') def build(bld): bld.add_subdirs('a b c d e f g h') bld.add_subdirs('callback') - if bld.env['HAVE_BOOST']: - bld.add_subdirs('shared_ptr') + #if bld.env['HAVE_BOOST']: + # bld.add_subdirs('shared_ptr') def configure(conf): - conf.env['HAVE_BOOST'] = conf.check_boost() + pass + #conf.env['HAVE_BOOST'] = conf.check_boost() From 7f4ef9ae4e77d629f6cd0f4e2a9f9448d8bdcc2a Mon Sep 17 00:00:00 2001 From: "Gustavo J. A. M. Carneiro" Date: Sun, 27 Mar 2011 16:17:55 +0100 Subject: [PATCH 05/20] Be less verbose with error importing wrapper registries from other modules --- pybindgen/wrapper_registry.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pybindgen/wrapper_registry.py b/pybindgen/wrapper_registry.py index b99995a..820d863 100644 --- a/pybindgen/wrapper_registry.py +++ b/pybindgen/wrapper_registry.py @@ -93,7 +93,7 @@ class StdMapWrapperRegistry(WrapperRegistry): % (module_pyobj_var, self.map_name)) code_block.write_code("if (_cobj == NULL) {\n" " _%(MAP)s = NULL;\n" - " PyErr_Print();\n" + " PyErr_Clear();\n" "} else {\n" " _%(MAP)s = reinterpret_cast< std::map *> (PyCObject_AsVoidPtr (_cobj));\n" " Py_DECREF(_cobj);\n" From 6727327367888031fd1ec55d6a2ecd860b31fa0a Mon Sep 17 00:00:00 2001 From: "Gustavo J. A. M. Carneiro" Date: Wed, 30 Mar 2011 18:06:07 +0100 Subject: [PATCH 06/20] Add __str__ for CppConstructor, to ease debugging --- pybindgen/cppmethod.py | 23 ++++++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/pybindgen/cppmethod.py b/pybindgen/cppmethod.py index ca96685..8e4959c 100644 --- a/pybindgen/cppmethod.py +++ b/pybindgen/cppmethod.py @@ -714,6 +714,28 @@ class CppConstructor(ForwardWrapperBase): code_sink.writeln('return 0;') self.write_close_wrapper(code_sink) + def __str__(self): + if not hasattr(self, '_class'): + return object.__str__(self) + + if self._class is None: + cls_name = "???" + else: + cls_name = self._class.full_name + + if self.return_value is None: + retval = "retval?" + else: + retval = self.return_value.ctype + + if self.parameters is None: + params = 'params?' + else: + params = ', '.join(["%s %s" % (param.ctype, param.name) for param in self.parameters]) + + return ("%s: %s %s::%s (%s);" % + (self.visibility, retval, cls_name, cls_name, params)) + class CppFunctionAsConstructor(CppConstructor): """ @@ -738,7 +760,6 @@ class CppFunctionAsConstructor(CppConstructor): unblock_threads = settings.unblock_threads parameters = [utils.eval_param(param, self) for param in parameters] - super(CppFunctionAsConstructor, self).__init__(parameters) self.c_function_name = c_function_name self.function_return_value = return_value From d35303cc3bdc73c400bec0cdfebe709537fdc3f8 Mon Sep 17 00:00:00 2001 From: "Gustavo J. A. M. Carneiro" Date: Mon, 4 Apr 2011 12:30:47 +0100 Subject: [PATCH 07/20] Add some missing python wrapper flags initializations --- pybindgen/cppmethod.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/pybindgen/cppmethod.py b/pybindgen/cppmethod.py index 8e4959c..81384d7 100644 --- a/pybindgen/cppmethod.py +++ b/pybindgen/cppmethod.py @@ -618,6 +618,7 @@ class CppConstructor(ForwardWrapperBase): if class_.helper_class is None: class_.write_create_instance(self.before_call, "self->obj", ", ".join(self.call_params)) class_.write_post_instance_creation_code(self.before_call, "self->obj", ", ".join(self.call_params)) + self.before_call.write_code("self->flags = PYBINDGEN_WRAPPER_FLAG_NONE;") else: ## We should only create a helper class instance when ## being called from a user python subclass. @@ -627,6 +628,7 @@ class CppConstructor(ForwardWrapperBase): class_.write_create_instance(self.before_call, "self->obj", ", ".join(self.call_params), class_.helper_class.name) + self.before_call.write_code("self->flags = PYBINDGEN_WRAPPER_FLAG_NONE;") self.before_call.write_code('((%s*) self->obj)->set_pyobj((PyObject *)self);' % class_.helper_class.name) class_.write_post_instance_creation_code(self.before_call, "self->obj", ", ".join(self.call_params), @@ -647,6 +649,7 @@ class CppConstructor(ForwardWrapperBase): self.before_call.write_code('return -1;') else: class_.write_create_instance(self.before_call, "self->obj", ", ".join(self.call_params)) + self.before_call.write_code("self->flags = PYBINDGEN_WRAPPER_FLAG_NONE;") class_.write_post_instance_creation_code(self.before_call, "self->obj", ", ".join(self.call_params)) self.before_call.unindent() From a5b2f0a1c04a0afe5408f70dfa63cd0f06ae83eb Mon Sep 17 00:00:00 2001 From: "Gustavo J. A. M. Carneiro" Date: Mon, 4 Apr 2011 19:42:55 +0100 Subject: [PATCH 08/20] Fix a cross-dll TypeMap bug --- pybindgen/cppclass.py | 35 ++++++++++++++++++++++++++++++++--- 1 file changed, 32 insertions(+), 3 deletions(-) diff --git a/pybindgen/cppclass.py b/pybindgen/cppclass.py index 3466058..41d1708 100644 --- a/pybindgen/cppclass.py +++ b/pybindgen/cppclass.py @@ -1204,16 +1204,19 @@ class CppClass(object): code_sink.writeln(''' #include +#include #include #if defined(__GNUC__) && __GNUC__ >= 3 # include #endif +#define PBG_TYPEMAP_DEBUG 0 + namespace pybindgen { class TypeMap { - std::map m_map; + std::map m_map; public: @@ -1221,11 +1224,22 @@ public: void register_wrapper(const std::type_info &cpp_type_info, PyTypeObject *python_wrapper) { - m_map[cpp_type_info.name()] = python_wrapper; + +#if PBG_TYPEMAP_DEBUG + std::cerr << "register_wrapper(this=" << this << ", type_name=" << cpp_type_info.name() + << ", python_wrapper=" << python_wrapper->tp_name << ")" << std::endl; +#endif + + m_map[std::string(cpp_type_info.name())] = python_wrapper; } PyTypeObject * lookup_wrapper(const std::type_info &cpp_type_info, PyTypeObject *fallback_wrapper) { + +#if PBG_TYPEMAP_DEBUG + std::cerr << "lookup_wrapper(this=" << this << ", type_name=" << cpp_type_info.name() << ")" << std::endl; +#endif + PyTypeObject *python_wrapper = m_map[cpp_type_info.name()]; if (python_wrapper) return python_wrapper; @@ -1236,8 +1250,23 @@ public: // registered python wrapper. const abi::__si_class_type_info *_typeinfo = dynamic_cast (&cpp_type_info); - while (_typeinfo && (python_wrapper = m_map[_typeinfo->name()]) == 0) +#if PBG_TYPEMAP_DEBUG + std::cerr << " -> looking at C++ type " << _typeinfo->name() << std::endl; +#endif + while (_typeinfo && (python_wrapper = m_map[std::string(_typeinfo->name())]) == 0) { _typeinfo = dynamic_cast (_typeinfo->__base_type); +#if PBG_TYPEMAP_DEBUG + std::cerr << " -> looking at C++ type " << _typeinfo->name() << std::endl; +#endif + } + +#if PBG_TYPEMAP_DEBUG + if (python_wrapper) { + std::cerr << " -> found match " << std::endl; + } else { + std::cerr << " -> return fallback wrapper" << std::endl; + } +#endif return python_wrapper? python_wrapper : fallback_wrapper; From 668e95268819ced087a9f6b8422f326af4285e33 Mon Sep 17 00:00:00 2001 From: Mathieu Lacage Date: Wed, 13 Apr 2011 10:41:03 +0100 Subject: [PATCH 09/20] Add some integer type aliases --- pybindgen/typehandlers/inttype.py | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/pybindgen/typehandlers/inttype.py b/pybindgen/typehandlers/inttype.py index c602acb..f58debe 100644 --- a/pybindgen/typehandlers/inttype.py +++ b/pybindgen/typehandlers/inttype.py @@ -329,7 +329,7 @@ class UInt8Return(ReturnValue): class UnsignedLongLongParam(Parameter): DIRECTIONS = [Parameter.DIRECTION_IN] - CTYPES = ['unsigned long long', 'uint64_t'] + CTYPES = ['unsigned long long', 'uint64_t', 'unsigned long long int'] def get_ctype_without_ref(self): return str(self.type_traits.ctype_no_const) @@ -346,7 +346,7 @@ class UnsignedLongLongParam(Parameter): class UnsignedLongLongRefParam(UnsignedLongLongParam): DIRECTIONS = [Parameter.DIRECTION_IN] - CTYPES = ['unsigned long long&', 'uint64_t&'] + CTYPES = ['unsigned long long&', 'uint64_t&', 'long long unsigned int &'] def get_ctype_without_ref(self): assert self.type_traits.target is not None @@ -369,7 +369,7 @@ class UnsignedLongLongReturn(ReturnValue): class UnsignedLongParam(Parameter): DIRECTIONS = [Parameter.DIRECTION_IN] - CTYPES = ['unsigned long'] + CTYPES = ['unsigned long', 'unsigned long int', 'long unsigned', 'long unsigned int'] def get_ctype_without_ref(self): return str(self.type_traits.ctype_no_const) @@ -386,7 +386,7 @@ class UnsignedLongParam(Parameter): class UnsignedLongRefParam(UnsignedLongParam): DIRECTIONS = [Parameter.DIRECTION_IN] - CTYPES = ['unsigned long&'] + CTYPES = ['unsigned long&', 'long unsigned&', 'long unsigned int&', 'unsigned long int&'] def get_ctype_without_ref(self): assert self.type_traits.target is not None @@ -448,7 +448,7 @@ class SizeTParam(Parameter): class LongLongParam(Parameter): DIRECTIONS = [Parameter.DIRECTION_IN] - CTYPES = ['long long', 'int64_t'] + CTYPES = ['long long', 'int64_t', 'long long int'] def get_ctype_without_ref(self): return str(self.type_traits.ctype_no_const) @@ -466,16 +466,15 @@ class LongLongParam(Parameter): class LongLongRefParam(LongLongParam): DIRECTIONS = [Parameter.DIRECTION_IN] # other directions not yet implemented - CTYPES = ['long long&', 'int64_t&'] + CTYPES = ['long long&', 'int64_t&', 'long long int&'] def get_ctype_without_ref(self): assert self.type_traits.target is not None return str(self.type_traits.target) - class LongLongReturn(ReturnValue): - CTYPES = ['long long', 'int64_t'] + CTYPES = ['long long', 'int64_t', 'long long int'] def get_c_error_return(self): return "return 0;" From b9aa718f8b751e74ad91823ccc1ee149a7ee0373 Mon Sep 17 00:00:00 2001 From: Mathieu Lacage Date: Fri, 15 Apr 2011 13:43:34 +0100 Subject: [PATCH 10/20] Add more int type handlers. --- pybindgen/typehandlers/inttype.py | 167 +++++++++++++++++++++++++++++- 1 file changed, 163 insertions(+), 4 deletions(-) diff --git a/pybindgen/typehandlers/inttype.py b/pybindgen/typehandlers/inttype.py index f58debe..2ca6cf8 100644 --- a/pybindgen/typehandlers/inttype.py +++ b/pybindgen/typehandlers/inttype.py @@ -193,6 +193,27 @@ class IntRefParam(Parameter): if self.direction & self.DIRECTION_OUT: wrapper.build_params.add_parameter("i", [name]) +class UnsignedIntRefParam(Parameter): + + DIRECTIONS = [Parameter.DIRECTION_IN, Parameter.DIRECTION_OUT, + Parameter.DIRECTION_IN|Parameter.DIRECTION_OUT] + CTYPES = ['unsigned int&', 'unsigned &'] + + def convert_c_to_python(self, wrapper): + if self.direction & self.DIRECTION_IN: + wrapper.build_params.add_parameter('I', [self.value]) + if self.direction & self.DIRECTION_OUT: + wrapper.parse_params.add_parameter("I", [self.value], self.name) + + def convert_python_to_c(self, wrapper): + #assert self.ctype == 'int&' + name = wrapper.declarations.declare_variable(self.ctype_no_const[:-1], self.name) + wrapper.call_params.append(name) + if self.direction & self.DIRECTION_IN: + wrapper.parse_params.add_parameter('I', ['&'+name], self.name) + if self.direction & self.DIRECTION_OUT: + wrapper.build_params.add_parameter("I", [name]) + class UInt16Return(ReturnValue): @@ -250,6 +271,28 @@ class UInt16Param(Parameter): 'PyErr_SetString(PyExc_ValueError, "Out of range");') wrapper.call_params.append(name) +class UInt16RefParam(Parameter): + + DIRECTIONS = [Parameter.DIRECTION_IN, Parameter.DIRECTION_INOUT, Parameter.DIRECTION_OUT] + CTYPES = ['uint16_t&', 'unsigned short&', 'unsigned short int&', 'short unsigned&', 'short unsigned int&'] + + def convert_c_to_python(self, wrapper): + assert isinstance(wrapper, ReverseWrapperBase) + if self.direction & self.DIRECTION_IN: + wrapper.build_params.add_parameter('H', [self.value]) + if self.direction & self.DIRECTION_OUT: + wrapper.parse_params.add_parameter("H", [self.value], self.name) + + def convert_python_to_c(self, wrapper): + name = wrapper.declarations.declare_variable(self.ctype_no_const[:-1], self.name) + wrapper.call_params.append(name) + if self.direction & self.DIRECTION_IN: + wrapper.parse_params.add_parameter('H', ['&'+name], self.name) + if self.direction & self.DIRECTION_OUT: + wrapper.build_params.add_parameter("H", [name]) + + + class Int16Param(Parameter): DIRECTIONS = [Parameter.DIRECTION_IN] @@ -292,7 +335,7 @@ class Int16RefParam(Parameter): class UInt8Param(Parameter): DIRECTIONS = [Parameter.DIRECTION_IN] - CTYPES = ['uint8_t'] + CTYPES = ['uint8_t', 'unsigned char int', 'char unsigned int', 'unsigned char', 'char unsigned'] def convert_c_to_python(self, wrapper): assert isinstance(wrapper, ReverseWrapperBase) @@ -306,10 +349,31 @@ class UInt8Param(Parameter): 'PyErr_SetString(PyExc_ValueError, "Out of range");') wrapper.call_params.append(name) +class UInt8RefParam(Parameter): + + DIRECTIONS = [Parameter.DIRECTION_IN, Parameter.DIRECTION_INOUT, Parameter.DIRECTION_OUT] + CTYPES = ['uint8_t&', 'unsigned char&', 'char unsigned&', 'unsigned char int&', 'char unsigned int&'] + + def convert_c_to_python(self, wrapper): + assert isinstance(wrapper, ReverseWrapperBase) + if self.direction & self.DIRECTION_IN: + wrapper.build_params.add_parameter('B', [self.value]) + if self.direction & self.DIRECTION_OUT: + wrapper.parse_params.add_parameter("B", [self.value], self.name) + + def convert_python_to_c(self, wrapper): + name = wrapper.declarations.declare_variable(self.ctype_no_const[:-1], self.name) + wrapper.call_params.append(name) + if self.direction & self.DIRECTION_IN: + wrapper.parse_params.add_parameter('B', ['&'+name], self.name) + if self.direction & self.DIRECTION_OUT: + wrapper.build_params.add_parameter("B", [name]) + + class UInt8Return(ReturnValue): - CTYPES = ['uint8_t'] + CTYPES = ['uint8_t', 'unsigned char', 'char unsigned', 'unsigned char int', 'char unsigned int'] def get_c_error_return(self): return "return 0;" @@ -325,11 +389,67 @@ class UInt8Return(ReturnValue): def convert_c_to_python(self, wrapper): wrapper.build_params.add_parameter("i", ['(int)' + self.value], prepend=True) +class Int8Param(Parameter): + + DIRECTIONS = [Parameter.DIRECTION_IN] + CTYPES = ['int8_t', 'signed char int', 'char signed int', 'signed char', 'char signed', 'char int', 'int char'] + + def convert_c_to_python(self, wrapper): + assert isinstance(wrapper, ReverseWrapperBase) + wrapper.build_params.add_parameter('i', ["(int) "+self.value]) + + def convert_python_to_c(self, wrapper): + assert isinstance(wrapper, ForwardWrapperBase) + name = wrapper.declarations.declare_variable("int", self.name, self.default_value) + wrapper.parse_params.add_parameter('i', ['&'+name], self.name, optional=bool(self.default_value)) + wrapper.before_call.write_error_check('%s > 0x7f' % name, + 'PyErr_SetString(PyExc_ValueError, "Out of range");') + wrapper.call_params.append(name) + +class Int8RefParam(Parameter): + + DIRECTIONS = [Parameter.DIRECTION_IN, Parameter.DIRECTION_INOUT, Parameter.DIRECTION_OUT] + CTYPES = ['int8_t&', 'signed char &', 'char signed&', 'signed char int&', 'char signed int&'] + + def convert_c_to_python(self, wrapper): + assert isinstance(wrapper, ReverseWrapperBase) + if self.direction & self.DIRECTION_IN: + wrapper.build_params.add_parameter('b', [self.value]) + if self.direction & self.DIRECTION_OUT: + wrapper.parse_params.add_parameter("b", [self.value], self.name) + + def convert_python_to_c(self, wrapper): + name = wrapper.declarations.declare_variable(self.ctype_no_const[:-1], self.name) + wrapper.call_params.append(name) + if self.direction & self.DIRECTION_IN: + wrapper.parse_params.add_parameter('b', ['&'+name], self.name) + if self.direction & self.DIRECTION_OUT: + wrapper.build_params.add_parameter("b", [name]) + +class Int8Return(ReturnValue): + + CTYPES = ['int8_t', 'char int', 'signed char', 'signed char int'] + + def get_c_error_return(self): + return "return 0;" + + def convert_python_to_c(self, wrapper): + tmp_var = wrapper.declarations.declare_variable("int", "tmp") + wrapper.parse_params.add_parameter("i", ["&"+tmp_var], prepend=True) + wrapper.after_call.write_error_check('%s > 128 || %s < -127' % (tmp_var, tmp_var), + 'PyErr_SetString(PyExc_ValueError, "Out of range");') + wrapper.after_call.write_code( + "%s = %s;" % (self.value, tmp_var)) + + def convert_c_to_python(self, wrapper): + wrapper.build_params.add_parameter("i", [self.value], prepend=True) + + class UnsignedLongLongParam(Parameter): DIRECTIONS = [Parameter.DIRECTION_IN] - CTYPES = ['unsigned long long', 'uint64_t', 'unsigned long long int'] + CTYPES = ['unsigned long long', 'uint64_t', 'unsigned long long int', 'long long unsigned int', 'long long unsigned'] def get_ctype_without_ref(self): return str(self.type_traits.ctype_no_const) @@ -346,7 +466,7 @@ class UnsignedLongLongParam(Parameter): class UnsignedLongLongRefParam(UnsignedLongLongParam): DIRECTIONS = [Parameter.DIRECTION_IN] - CTYPES = ['unsigned long long&', 'uint64_t&', 'long long unsigned int &'] + CTYPES = ['unsigned long long&', 'uint64_t&', 'long long unsigned int&'] def get_ctype_without_ref(self): assert self.type_traits.target is not None @@ -405,6 +525,45 @@ class UnsignedLongReturn(ReturnValue): def convert_c_to_python(self, wrapper): wrapper.build_params.add_parameter("k", [self.value], prepend=True) +class LongParam(Parameter): + + DIRECTIONS = [Parameter.DIRECTION_IN] + CTYPES = ['signed long', 'signed long int', 'long', 'long int', 'long signed', 'long signed int'] + + def get_ctype_without_ref(self): + return str(self.type_traits.ctype_no_const) + + def convert_c_to_python(self, wrapper): + assert isinstance(wrapper, ReverseWrapperBase) + wrapper.build_params.add_parameter('l', [self.value]) + + def convert_python_to_c(self, wrapper): + assert isinstance(wrapper, ForwardWrapperBase) + name = wrapper.declarations.declare_variable(self.get_ctype_without_ref(), self.name, self.default_value) + wrapper.parse_params.add_parameter('l', ['&'+name], self.name, optional=bool(self.default_value)) + wrapper.call_params.append(name) + +class LongRefParam(LongParam): + DIRECTIONS = [Parameter.DIRECTION_IN] + CTYPES = ['signed long&', 'long signed&', 'long&', 'long int&', 'long signed int&', 'signed long int&'] + + def get_ctype_without_ref(self): + assert self.type_traits.target is not None + return str(self.type_traits.target) + +class LongReturn(ReturnValue): + + CTYPES = ['signed long', 'long signed int', 'long', 'long int'] + + def get_c_error_return(self): + return "return 0;" + + def convert_python_to_c(self, wrapper): + wrapper.parse_params.add_parameter("l", ["&"+self.value], prepend=True) + + def convert_c_to_python(self, wrapper): + wrapper.build_params.add_parameter("l", [self.value], prepend=True) + class SizeTReturn(ReturnValue): From 2d10262b282dd7c640418db3cedce614910e2a55 Mon Sep 17 00:00:00 2001 From: "Gustavo J. A. M. Carneiro" Date: Fri, 15 Apr 2011 13:47:40 +0100 Subject: [PATCH 11/20] Disable the char+int type registrations, they cause unit test build failures --- pybindgen/typehandlers/inttype.py | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/pybindgen/typehandlers/inttype.py b/pybindgen/typehandlers/inttype.py index 2ca6cf8..c586019 100644 --- a/pybindgen/typehandlers/inttype.py +++ b/pybindgen/typehandlers/inttype.py @@ -335,7 +335,7 @@ class Int16RefParam(Parameter): class UInt8Param(Parameter): DIRECTIONS = [Parameter.DIRECTION_IN] - CTYPES = ['uint8_t', 'unsigned char int', 'char unsigned int', 'unsigned char', 'char unsigned'] + CTYPES = ['uint8_t', 'unsigned char', 'char unsigned'] def convert_c_to_python(self, wrapper): assert isinstance(wrapper, ReverseWrapperBase) @@ -352,7 +352,7 @@ class UInt8Param(Parameter): class UInt8RefParam(Parameter): DIRECTIONS = [Parameter.DIRECTION_IN, Parameter.DIRECTION_INOUT, Parameter.DIRECTION_OUT] - CTYPES = ['uint8_t&', 'unsigned char&', 'char unsigned&', 'unsigned char int&', 'char unsigned int&'] + CTYPES = ['uint8_t&', 'unsigned char&', 'char unsigned&'] def convert_c_to_python(self, wrapper): assert isinstance(wrapper, ReverseWrapperBase) @@ -373,7 +373,7 @@ class UInt8RefParam(Parameter): class UInt8Return(ReturnValue): - CTYPES = ['uint8_t', 'unsigned char', 'char unsigned', 'unsigned char int', 'char unsigned int'] + CTYPES = ['uint8_t', 'unsigned char', 'char unsigned'] def get_c_error_return(self): return "return 0;" @@ -392,7 +392,7 @@ class UInt8Return(ReturnValue): class Int8Param(Parameter): DIRECTIONS = [Parameter.DIRECTION_IN] - CTYPES = ['int8_t', 'signed char int', 'char signed int', 'signed char', 'char signed', 'char int', 'int char'] + CTYPES = ['int8_t', 'signed char', 'char signed'] def convert_c_to_python(self, wrapper): assert isinstance(wrapper, ReverseWrapperBase) @@ -409,7 +409,7 @@ class Int8Param(Parameter): class Int8RefParam(Parameter): DIRECTIONS = [Parameter.DIRECTION_IN, Parameter.DIRECTION_INOUT, Parameter.DIRECTION_OUT] - CTYPES = ['int8_t&', 'signed char &', 'char signed&', 'signed char int&', 'char signed int&'] + CTYPES = ['int8_t&', 'signed char &', 'char signed&'] def convert_c_to_python(self, wrapper): assert isinstance(wrapper, ReverseWrapperBase) @@ -428,7 +428,7 @@ class Int8RefParam(Parameter): class Int8Return(ReturnValue): - CTYPES = ['int8_t', 'char int', 'signed char', 'signed char int'] + CTYPES = ['int8_t', 'signed char'] def get_c_error_return(self): return "return 0;" From 7ba02242f83ec77da1aedad96e3c3bae916defc9 Mon Sep 17 00:00:00 2001 From: "Gustavo J. A. M. Carneiro" Date: Tue, 10 May 2011 19:10:18 +0100 Subject: [PATCH 12/20] Add support for 'throw' annotations in functions and methods --- pybindgen/gccxmlparser.py | 21 +++++++++++++++++++++ tests/foo.cc | 20 ++++++++++++++++++++ tests/foo.h | 9 +++++++++ tests/foomodulegen.py | 5 +++++ tests/footest.py | 23 +++++++++++++++++++++++ 5 files changed, 78 insertions(+) diff --git a/pybindgen/gccxmlparser.py b/pybindgen/gccxmlparser.py index 4859f21..bc1c501 100644 --- a/pybindgen/gccxmlparser.py +++ b/pybindgen/gccxmlparser.py @@ -1708,6 +1708,8 @@ pybindgen.settings.error_handler = ErrorHandler() kwargs['unblock_threads'] = annotations_scanner.parse_boolean(val) elif key == 'name': kwargs['custom_name'] = val + elif key == 'throw': + kwargs['throw'] = self._get_annotation_exceptions(val) else: warnings.warn_explicit("Annotation '%s=%s' not used (used in %s)" % (key, val, member), @@ -1997,6 +1999,23 @@ pybindgen.settings.error_handler = ErrorHandler() WrapperWarning, calldef.location.file_name, calldef.location.line) return retval + def _get_annotation_exceptions(self, annotation): + retval = [] + for exc_name in annotation.split(','): + traits = ctypeparser.TypeTraits(normalize_name(exc_name)) + if traits.type_is_reference: + name = str(traits.target) + else: + name = str(traits.ctype) + exc = self.type_registry.root_module.get(name, None) + if isinstance(exc, CppException): + retval.append(exc) + else: + warnings.warn_explicit("Thrown exception '%s' was not previously detected as an exception class." + " PyBindGen bug?" + % (normalize_name(decl.partial_decl_string)), + WrapperWarning, calldef.location.file_name, calldef.location.line) + return retval def scan_functions(self): self._stage = 'scan functions' @@ -2069,6 +2088,8 @@ pybindgen.settings.error_handler = ErrorHandler() pass elif name == 'unblock_threads': kwargs['unblock_threads'] = annotations_scanner.parse_boolean(value) + elif name == 'throw': + kwargs['throw'] = self._get_annotation_exceptions(value) else: warnings.warn_explicit("Incorrect annotation %s=%s" % (name, value), AnnotationsWarning, fun.location.file_name, fun.location.line) diff --git a/tests/foo.cc b/tests/foo.cc index 1994e49..1073e94 100644 --- a/tests/foo.cc +++ b/tests/foo.cc @@ -507,6 +507,16 @@ my_inverse_func2 (double x) throw (std::exception) return 1/x; } +double +my_inverse_func3 (double x) +{ + if (x == 0) + { + throw std::runtime_error ("value must be != 0"); + } + return 1/x; +} + double ClassThatThrows::my_inverse_method2 (double x) throw (std::exception) { @@ -516,3 +526,13 @@ ClassThatThrows::my_inverse_method2 (double x) throw (std::exception) } return 1/x; } + +double +ClassThatThrows::my_inverse_method3 (double x) +{ + if (x == 0) + { + throw std::runtime_error ("value must be != 0"); + } + return 1/x; +} diff --git a/tests/foo.h b/tests/foo.h index aab29ac..c91adce 100644 --- a/tests/foo.h +++ b/tests/foo.h @@ -1079,6 +1079,10 @@ struct DomainError : public Error double my_inverse_func (double x) throw (DomainError); double my_inverse_func2 (double x) throw (std::exception); +// the following function throws an exception but forgets to declare it +// -#- throw=std::exception -#- +double my_inverse_func3 (double x); + class ClassThatThrows { public: @@ -1088,7 +1092,12 @@ public: double my_inverse_method (double x) throw (DomainError); double my_inverse_method2 (double x) throw (std::exception); + // the following method throws an exception but forgets to declare it + // -#- throw=std::exception -#- + double my_inverse_method3 (double x); + virtual int throw_error () const throw (std::exception); + }; diff --git a/tests/foomodulegen.py b/tests/foomodulegen.py index 4450042..11e7d9a 100755 --- a/tests/foomodulegen.py +++ b/tests/foomodulegen.py @@ -531,6 +531,11 @@ int %s::custom_method_added_by_a_hook(int x) ClassThatThrows.add_method('my_inverse_method2', 'double', [Parameter.new('double', 'x')], throw=[std_exception]) + mod.add_function('my_inverse_func3', 'double', [Parameter.new('double', 'x')], + throw=[std_exception]) + ClassThatThrows.add_method('my_inverse_method3', 'double', [Parameter.new('double', 'x')], + throw=[std_exception]) + ClassThatThrows.add_method('throw_error', 'int', [], throw=[std_exception], is_const=True, is_virtual=True) # https://bugs.launchpad.net/pybindgen/+bug/450255 diff --git a/tests/footest.py b/tests/footest.py index 55150d9..80d925b 100644 --- a/tests/footest.py +++ b/tests/footest.py @@ -1212,6 +1212,28 @@ class TestFoo(unittest.TestCase): msg = str(ex) self.assertEqual(msg, "value must be != 0") + def test_function_exception3(self): + y = foo.my_inverse_func3(2) + self.assertEqual(y, 0.5) + self.assertRaises(foo.exception, foo.my_inverse_func2, 0) + try: + foo.my_inverse_func3(0) + except foo.exception, ex: + msg = str(ex) + self.assertEqual(msg, "value must be != 0") + + def test_method_exception3(self): + c = foo.ClassThatThrows(1) + y = c.my_inverse_method3(2) + self.assertEqual(y, 0.5) + self.assertRaises(foo.exception, c.my_inverse_method3, 0) + try: + c.my_inverse_method3(0) + except foo.exception, ex: + msg = str(ex) + self.assertEqual(msg, "value must be != 0") + + def test_bug436154(self): r = foo.Foo.add_sub(1, 2) self.assertEqual(r, 3) @@ -1388,5 +1410,6 @@ class TestFoo(unittest.TestCase): s = some.method_returning_cstring() self.assertEqual(s, "another string") + if __name__ == '__main__': unittest.main() From 3ac1a30e355223c49df794829667624626d3c13a Mon Sep 17 00:00:00 2001 From: "Gustavo J. A. M. Carneiro" Date: Wed, 11 May 2011 16:14:39 +0100 Subject: [PATCH 13/20] Bug #780945: Exception translation generates invalid code if return value is wrapped (i.e. not primitive) --- pybindgen/cppmethod.py | 6 ++++++ pybindgen/function.py | 5 +++++ tests/foo.cc | 9 +++++++++ tests/foo.h | 2 ++ tests/foomodulegen.py | 4 ++++ 5 files changed, 26 insertions(+) diff --git a/pybindgen/cppmethod.py b/pybindgen/cppmethod.py index 81384d7..6f9772e 100644 --- a/pybindgen/cppmethod.py +++ b/pybindgen/cppmethod.py @@ -365,6 +365,11 @@ class CppMethod(ForwardWrapperBase): Returns the corresponding PyMethodDef entry string. """ + + if self.throw: # Bug #780945 + self.return_value.REQUIRES_ASSIGNMENT_CONSTRUCTOR = False + self.reset_code_generation_state() + class_ = self.class_ #assert isinstance(class_, CppClass) tmp_sink = codesink.MemoryCodeSink() @@ -681,6 +686,7 @@ class CppConstructor(ForwardWrapperBase): :returns: the wrapper function name. """ + if self.visibility == 'private': raise utils.SkipWrapper("Class %r has a private constructor ->" " cannot generate a constructor for it" % self._class.full_name) diff --git a/pybindgen/function.py b/pybindgen/function.py index dc61192..4e7d656 100644 --- a/pybindgen/function.py +++ b/pybindgen/function.py @@ -212,6 +212,11 @@ class Function(ForwardWrapperBase): :param code_sink: a CodeSink instance that will receive the generated code :param wrapper_name: name of wrapper function """ + + if self.throw: # Bug #780945 + self.return_value.REQUIRES_ASSIGNMENT_CONSTRUCTOR = False + self.reset_code_generation_state() + if wrapper_name is None: self.wrapper_actual_name = self.wrapper_base_name else: diff --git a/tests/foo.cc b/tests/foo.cc index 1073e94..f746c1d 100644 --- a/tests/foo.cc +++ b/tests/foo.cc @@ -536,3 +536,12 @@ ClassThatThrows::my_inverse_method3 (double x) } return 1/x; } + + +Tupl +my_throwing_func () throw (std::exception) +{ + Tupl retval; + return retval; +} + diff --git a/tests/foo.h b/tests/foo.h index c91adce..21c4633 100644 --- a/tests/foo.h +++ b/tests/foo.h @@ -1208,5 +1208,7 @@ public: }; +Tupl my_throwing_func () throw (std::exception); + #endif /* !FOO_H_ */ diff --git a/tests/foomodulegen.py b/tests/foomodulegen.py index 11e7d9a..9c458e3 100755 --- a/tests/foomodulegen.py +++ b/tests/foomodulegen.py @@ -575,6 +575,10 @@ int %s::custom_method_added_by_a_hook(int x) MIMixed.add_constructor([]) MIMixed.add_method('mixed_method', 'int', [], is_const=True) + + mod.add_function('my_throwing_func', 'Tupl', [], throw=[std_exception]) + + #### --- error handler --- class MyErrorHandler(pybindgen.settings.ErrorHandler): From bb0d076a885f2b937fddacc6c6e7b223729fb06f Mon Sep 17 00:00:00 2001 From: "Gustavo J. A. M. Carneiro" Date: Sun, 12 Jun 2011 12:40:18 +0100 Subject: [PATCH 14/20] Add a buffer example --- examples/buffer/c.cc | 25 +++++++++++++++++++++++++ examples/buffer/c.h | 6 ++++++ examples/buffer/c_test.py | 10 ++++++++++ examples/buffer/modulegen.py | 36 ++++++++++++++++++++++++++++++++++++ examples/buffer/wscript | 20 ++++++++++++++++++++ examples/wscript | 1 + 6 files changed, 98 insertions(+) create mode 100644 examples/buffer/c.cc create mode 100644 examples/buffer/c.h create mode 100644 examples/buffer/c_test.py create mode 100644 examples/buffer/modulegen.py create mode 100644 examples/buffer/wscript diff --git a/examples/buffer/c.cc b/examples/buffer/c.cc new file mode 100644 index 0000000..67aa359 --- /dev/null +++ b/examples/buffer/c.cc @@ -0,0 +1,25 @@ +#include "c.h" + +static const int LEN = 1024*1024; + +static unsigned short int buffer[LEN] = {0,}; + +unsigned short int* GetBuffer() +{ + return buffer; +} + +int GetBufferLen() +{ + return LEN; +} + +unsigned short int GetBufferChecksum() +{ + unsigned short int sum = 0; + for (int i = 0; i < LEN; sum += buffer[i++]); + return sum; +} + + + diff --git a/examples/buffer/c.h b/examples/buffer/c.h new file mode 100644 index 0000000..4434bce --- /dev/null +++ b/examples/buffer/c.h @@ -0,0 +1,6 @@ + +unsigned short* GetBuffer(); +int GetBufferLen(); +unsigned short GetBufferChecksum(); + + diff --git a/examples/buffer/c_test.py b/examples/buffer/c_test.py new file mode 100644 index 0000000..6ed7e06 --- /dev/null +++ b/examples/buffer/c_test.py @@ -0,0 +1,10 @@ +import sys +sys.path.insert(0, "../../build/default/examples/buffer") +import c + +print c.GetBufferLen() +print c.GetBufferChecksum() +buf = c.GetBuffer() +buf[10] = chr(123) +print c.GetBufferChecksum() +print buf[10] diff --git a/examples/buffer/modulegen.py b/examples/buffer/modulegen.py new file mode 100644 index 0000000..4688222 --- /dev/null +++ b/examples/buffer/modulegen.py @@ -0,0 +1,36 @@ +#! /usr/bin/env python + +import sys + +import pybindgen +from pybindgen import ReturnValue, Parameter, Module, Function, FileCodeSink +from pybindgen import CppMethod, CppConstructor, CppClass, Enum +from pybindgen.typehandlers.base import ForwardWrapperBase + + +class BufferReturn(ReturnValue): + CTYPES = [] + + def __init__(self, ctype, length_expression): + super(BufferReturn, self).__init__(ctype, is_const=False) + self.length_expression = length_expression + + def convert_c_to_python(self, wrapper): + pybuf = wrapper.after_call.declare_variable("PyObject*", "pybuf") + wrapper.after_call.write_code("%s = PyBuffer_FromReadWriteMemory(retval, (%s)*sizeof(short int));" % (pybuf, self.length_expression)) + wrapper.build_params.add_parameter("N", [pybuf], prepend=True) + + +def my_module_gen(out_file): + + mod = Module('c') + mod.add_include('"c.h"') + + mod.add_function("GetBuffer", BufferReturn("unsigned short int*", "GetBufferLen()"), []) + mod.add_function("GetBufferLen", ReturnValue.new("int"), []) + mod.add_function("GetBufferChecksum", ReturnValue.new("unsigned short"), []) + + mod.generate(FileCodeSink(out_file)) + +if __name__ == '__main__': + my_module_gen(sys.stdout) diff --git a/examples/buffer/wscript b/examples/buffer/wscript new file mode 100644 index 0000000..e92200a --- /dev/null +++ b/examples/buffer/wscript @@ -0,0 +1,20 @@ +## -*- python -*- + +def build(bld): + + gen = bld.new_task_gen( + features='command', + source='modulegen.py', + target='cmodule.cc', + command='${PYTHON} ${SRC[0]} > ${TGT[0]}') + + if bld.env['CXX']: + obj = bld.new_task_gen('cxx', 'shlib', 'pyext') + obj.source = [ + 'c.cc', + 'cmodule.cc' + ] + obj.target = 'c' + obj.install_path = None # do not install + obj.includes = '.' + diff --git a/examples/wscript b/examples/wscript index 5b42dda..5512602 100644 --- a/examples/wscript +++ b/examples/wscript @@ -6,6 +6,7 @@ def set_options(opt): def build(bld): bld.add_subdirs('a b c d e f g h') bld.add_subdirs('callback') + bld.add_subdirs('buffer') #if bld.env['HAVE_BOOST']: # bld.add_subdirs('shared_ptr') From b7094b55febbeba298e76b7688b4af8d727f0902 Mon Sep 17 00:00:00 2001 From: "Gustavo J. A. M. Carneiro" Date: Thu, 16 Jun 2011 11:49:20 +0100 Subject: [PATCH 15/20] Add new destructor_visibility CppClass option --- pybindgen/cppclass.py | 18 ++++++++++++------ pybindgen/gccxmlparser.py | 15 ++++++++++++--- tests/foo.h | 17 +++++++++++++++++ tests/foomodulegen.py | 7 +++++++ tests/footest.py | 8 ++++++++ 5 files changed, 56 insertions(+), 9 deletions(-) diff --git a/pybindgen/cppclass.py b/pybindgen/cppclass.py index 41d1708..476ebd6 100644 --- a/pybindgen/cppclass.py +++ b/pybindgen/cppclass.py @@ -451,6 +451,7 @@ class CppClass(object): docstring=None, custom_name=None, import_from_module=None, + destructor_visibility='public' ): """ :param name: class name @@ -521,6 +522,8 @@ class CppClass(object): self.template_parameters = template_parameters self.container_traits = None self.import_from_module = import_from_module + assert destructor_visibility in ['public', 'private', 'protected'] + self.destructor_visibility = destructor_visibility self.custom_name = custom_name if custom_template_class_name: @@ -1827,6 +1830,7 @@ typedef struct { self._generate_gc_methods(code_sink) self._generate_destructor(code_sink, have_constructor) + if self.has_output_stream_operator: self._generate_str(code_sink) @@ -2255,12 +2259,14 @@ static PyObject*\n%s(%s *self) raise CodeGenerationError("Cannot finish generating class %s: " "type is incomplete, but no free/unref_function defined" % self.full_name) - delete_code = (" %s *tmp = self->obj;\n" - " self->obj = NULL;\n" - " if (!(self->flags&PYBINDGEN_WRAPPER_FLAG_OBJECT_NOT_OWNED)) {\n" - " delete tmp;\n" - " }" - % (self.full_name,)) + if self.destructor_visibility == 'public': + delete_code = (" %s *tmp = self->obj;\n" + " self->obj = NULL;\n" + " if (!(self->flags&PYBINDGEN_WRAPPER_FLAG_OBJECT_NOT_OWNED)) {\n" + " delete tmp;\n" + " }" % (self.full_name,)) + else: + delete_code = (" self->obj = NULL;\n") return delete_code def _generate_gc_methods(self, code_sink): diff --git a/pybindgen/gccxmlparser.py b/pybindgen/gccxmlparser.py index bc1c501..3175cfb 100644 --- a/pybindgen/gccxmlparser.py +++ b/pybindgen/gccxmlparser.py @@ -907,12 +907,21 @@ pybindgen.settings.error_handler = ErrorHandler() if self._class_has_virtual_methods(cls) and not cls.bases: kwargs.setdefault('allow_subclassing', True) - if not self._has_public_destructor(cls): - kwargs.setdefault('is_singleton', True) - #print >> sys.stderr, "##### class %s has no public destructor" % cls.decl_string + #if not self._has_public_destructor(cls): + # kwargs.setdefault('is_singleton', True) + # #print >> sys.stderr, "##### class %s has no public destructor" % cls.decl_string + + des = self._get_destructor_visibility(cls) + #print >> sys.stderr, "##### class %s destructor is %s" % (cls.decl_string, des) + if des != 'public': + kwargs.setdefault('destructor_visibility', des) return is_exception + def _get_destructor_visibility(self, cls): + for member in cls.get_members(): + if isinstance(member, calldef.destructor_t): + return member.access_type def _has_public_destructor(self, cls): for member in cls.get_members(): diff --git a/tests/foo.h b/tests/foo.h index 21c4633..6533ea7 100644 --- a/tests/foo.h +++ b/tests/foo.h @@ -1211,4 +1211,21 @@ public: Tupl my_throwing_func () throw (std::exception); +class IFoo +{ +public: + virtual void DoSomething() = 0; +protected: + virtual ~IFoo() {} +}; + + +class IFooImpl : public IFoo +{ +public: + virtual void DoSomething() {} + ~IFooImpl() {} +}; + + #endif /* !FOO_H_ */ diff --git a/tests/foomodulegen.py b/tests/foomodulegen.py index 9c458e3..3094ca4 100755 --- a/tests/foomodulegen.py +++ b/tests/foomodulegen.py @@ -579,6 +579,13 @@ int %s::custom_method_added_by_a_hook(int x) mod.add_function('my_throwing_func', 'Tupl', [], throw=[std_exception]) + IFoo = mod.add_class("IFoo", destructor_visibility='protected', allow_subclassing=True) + IFoo.add_method("DoSomething", None, [], is_pure_virtual=True) + + IFooImpl = mod.add_class("IFooImpl", parent=IFoo, destructor_visibility='public') + IFooImpl.add_constructor([]) + IFooImpl.add_method("DoSomething", None, [], is_virtual=True) + #### --- error handler --- class MyErrorHandler(pybindgen.settings.ErrorHandler): diff --git a/tests/footest.py b/tests/footest.py index 80d925b..8a5cb65 100644 --- a/tests/footest.py +++ b/tests/footest.py @@ -1410,6 +1410,14 @@ class TestFoo(unittest.TestCase): s = some.method_returning_cstring() self.assertEqual(s, "another string") + def test_protected_destructor(self): + f = foo.IFooImpl() + f.DoSomething() + del f + while gc.collect(): + pass + + if __name__ == '__main__': unittest.main() From 0b7f23150b989e3cfc78293401ccc1f226924bce Mon Sep 17 00:00:00 2001 From: "Gustavo J. A. M. Carneiro" Date: Wed, 22 Jun 2011 14:30:27 +0100 Subject: [PATCH 16/20] returning const* doesn't work with 'reference_existing_object' --- pybindgen/cppclass_typehandlers.py | 10 ++++++++-- tests/foo.h | 4 ++-- tests/foomodulegen.py | 4 ++-- 3 files changed, 12 insertions(+), 6 deletions(-) diff --git a/pybindgen/cppclass_typehandlers.py b/pybindgen/cppclass_typehandlers.py index cde4f57..d30c9b1 100644 --- a/pybindgen/cppclass_typehandlers.py +++ b/pybindgen/cppclass_typehandlers.py @@ -57,13 +57,19 @@ def common_shared_object_return(value, py_name, cpp_class, code_block, ## Assign the C++ value to the Python wrapper if caller_owns_return: - code_block.write_code("%s->obj = %s;" % (py_name, value_ptr)) + if type_traits.target_is_const: + code_block.write_code("%s->obj = (%s *) (%s);" % (py_name, cpp_class.full_name, value_ptr)) + else: + code_block.write_code("%s->obj = %s;" % (py_name, value_ptr)) code_block.write_code( "%s->flags = PYBINDGEN_WRAPPER_FLAG_NONE;" % (py_name,)) else: if not isinstance(cpp_class.memory_policy, cppclass.ReferenceCountingPolicy): if reference_existing_object: - code_block.write_code("%s->obj = %s;" % (py_name, value_ptr)) + if type_traits.target_is_const: + code_block.write_code("%s->obj = (%s *) (%s);" % (py_name, cpp_class.full_name, value_ptr)) + else: + code_block.write_code("%s->obj = %s;" % (py_name, value_ptr)) code_block.write_code( "%s->flags = PYBINDGEN_WRAPPER_FLAG_OBJECT_NOT_OWNED;" % (py_name,)) else: diff --git a/tests/foo.h b/tests/foo.h index 6533ea7..a977de9 100644 --- a/tests/foo.h +++ b/tests/foo.h @@ -362,7 +362,7 @@ public: } // -#- @return(caller_owns_return=false) -#- - Foo * get_foo_shared_ptr () { + const Foo * get_foo_shared_ptr () { return m_foo_shared_ptr; } @@ -1161,7 +1161,7 @@ public: virtual ~Box () { --instance_count;} // -#- @return(reference_existing_object=true) -#- - Foobar* getFoobarInternalPtr () { return &m_foobar; } + const Foobar* getFoobarInternalPtr () { return &m_foobar; } // -#- @return(reference_existing_object=true) -#- Foobar& getFoobarInternalRef () { return m_foobar; } diff --git a/tests/foomodulegen.py b/tests/foomodulegen.py index 3094ca4..9cbccfc 100755 --- a/tests/foomodulegen.py +++ b/tests/foomodulegen.py @@ -201,7 +201,7 @@ int %s::custom_method_added_by_a_hook(int x) SomeObject.add_method('set_foo_shared_ptr', ReturnValue.new('void'), [Parameter.new('Foo*', 'foo', transfer_ownership=False)]) - SomeObject.add_method('get_foo_shared_ptr', ReturnValue.new('Foo*', caller_owns_return=False), []) + SomeObject.add_method('get_foo_shared_ptr', ReturnValue.new('const Foo*', caller_owns_return=False), []) SomeObject.add_method('get_foo_ptr', ReturnValue.new('Foo*', caller_owns_return=True), []) SomeObject.add_method('set_foo_by_ref', ReturnValue.new('void'), @@ -551,7 +551,7 @@ int %s::custom_method_added_by_a_hook(int x) Box = mod.add_class('Box') Box.add_constructor([]) Box.add_static_attribute('instance_count', ReturnValue.new('int')) - Box.add_method('getFoobarInternalPtr', ReturnValue.new('Foobar*', reference_existing_object=True), []) + Box.add_method('getFoobarInternalPtr', ReturnValue.new('const Foobar*', reference_existing_object=True), []) Box.add_method('getFoobarInternalRef', ReturnValue.new('Foobar&', reference_existing_object=True), []) Box.add_method('getFoobarInternalPtr2', ReturnValue.new('Foobar*', return_internal_reference=True), []) Box.add_method('getFoobarInternalRef2', ReturnValue.new('Foobar&', return_internal_reference=True), []) From daffb90e2f4adcf5b89211bce256fff6674a9f29 Mon Sep 17 00:00:00 2001 From: "Gustavo J. A. M. Carneiro" Date: Tue, 19 Jul 2011 19:39:45 +0100 Subject: [PATCH 17/20] Don't wrap template instantiation classes when one of the template parameters is a private class --- pybindgen/gccxmlparser.py | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/pybindgen/gccxmlparser.py b/pybindgen/gccxmlparser.py index 3175cfb..33ddcf9 100644 --- a/pybindgen/gccxmlparser.py +++ b/pybindgen/gccxmlparser.py @@ -1180,6 +1180,20 @@ pybindgen.settings.error_handler = ErrorHandler() template_parameters_decls = [find_declaration_from_name(self.global_ns, templ_param) for templ_param in template_parameters] + ignore_class = False + for template_param in template_parameters_decls: + if not isinstance(template_param, class_t): + continue + if not isinstance(template_param.parent, class_t): + continue + access = template_param.parent.find_out_member_access_type(template_param) + if access != 'public': + # this templated class depends on a private type => we can't wrap it + ignore_class = True + break + if ignore_class: + continue + if 0: # this is disabled due to ns3 ## if any template argument is a class that is not yet ## registered, postpone scanning/registering the template From ac966d7dd2aa7e14a24ba2fb2a0106b761473db0 Mon Sep 17 00:00:00 2001 From: "Gustavo J. A. M. Carneiro" Date: Tue, 19 Jul 2011 19:49:04 +0100 Subject: [PATCH 18/20] Cannot allow subclassing if a destructor is private --- pybindgen/cppclass.py | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/pybindgen/cppclass.py b/pybindgen/cppclass.py index 476ebd6..a88691f 100644 --- a/pybindgen/cppclass.py +++ b/pybindgen/cppclass.py @@ -633,7 +633,11 @@ class CppClass(object): else: if any([p.allow_subclassing for p in self.bases]) and not allow_subclassing: raise ValueError("Cannot disable subclassing if a parent class allows it") - self.allow_subclassing = allow_subclassing + else: + self.allow_subclassing = allow_subclassing + + if self.destructor_visibility in ['public', 'protected']: + self.allow_subclassing = False self.typeid_map_name = None From 6e01487ac3794a380ac7c043afd54a722b827008 Mon Sep 17 00:00:00 2001 From: "Gustavo J. A. M. Carneiro" Date: Wed, 20 Jul 2011 12:25:52 +0100 Subject: [PATCH 19/20] Fix typo in previous patch --- pybindgen/cppclass.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pybindgen/cppclass.py b/pybindgen/cppclass.py index a88691f..dbfb581 100644 --- a/pybindgen/cppclass.py +++ b/pybindgen/cppclass.py @@ -636,7 +636,7 @@ class CppClass(object): else: self.allow_subclassing = allow_subclassing - if self.destructor_visibility in ['public', 'protected']: + if self.destructor_visibility not in ['public', 'protected']: self.allow_subclassing = False self.typeid_map_name = None From 811470ae34e46d4dfbd3762159201bba40b5cd9f Mon Sep 17 00:00:00 2001 From: Claudio Freire <> Date: Wed, 20 Jul 2011 12:42:04 +0100 Subject: [PATCH 20/20] cppclass _generate_import_from_module generates invalid return at module initialization time --- pybindgen/cppclass.py | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/pybindgen/cppclass.py b/pybindgen/cppclass.py index dbfb581..2e0271f 100644 --- a/pybindgen/cppclass.py +++ b/pybindgen/cppclass.py @@ -1712,6 +1712,11 @@ typedef struct { return class_python_name def _generate_import_from_module(self, code_sink, module): + if module.parent is None: + error_retcode = "" + else: + error_retcode = "NULL" + # TODO: skip this step if the requested typestructure is never used if ' named ' in self.import_from_module: module_name, type_name = self.import_from_module.split(" named ") @@ -1723,8 +1728,8 @@ typedef struct { module.after_init.write_code("PyObject *module = PyImport_ImportModule(\"%s\");" % module_name) module.after_init.write_code( "if (module == NULL) {\n" - " return;\n" - "}") + " return %s;\n" + "}" % (error_retcode,)) module.after_init.write_code("_%s = (PyTypeObject*) PyObject_GetAttrString(module, \"%s\");\n" % (self.pytypestruct, self.get_python_name()))