diff --git a/pybindgen/cppclass.py b/pybindgen/cppclass.py index 1f06aab..9cec1dc 100644 --- a/pybindgen/cppclass.py +++ b/pybindgen/cppclass.py @@ -1085,6 +1085,17 @@ public: self.has_trivial_constructor = True def add_output_stream_operator(self): + """ + Add str() support based on C++ output stream operator. + + Calling this method enables wrapping of an assumed to be defined operator function:: + + std::ostream & operator << (std::ostream &, MyClass const &); + + The wrapper will be registered as an str() python operator, + and will call the C++ operator function to convert the value + to a string. + """ self.has_output_stream_operator = True def add_constructor(self, *args, **kwargs): diff --git a/pybindgen/gccxmlparser.py b/pybindgen/gccxmlparser.py index c5792ec..292d45c 100644 --- a/pybindgen/gccxmlparser.py +++ b/pybindgen/gccxmlparser.py @@ -1507,6 +1507,7 @@ pybindgen.settings.error_handler = ErrorHandler() class_wrapper.ThisClassRefParameter("%s const &" % class_wrapper.full_name, 'ctor_arg', is_const=True)]) if has_output_stream_operator: + class_wrapper.add_output_stream_operator() pygen_sink.writeln("cls.add_output_stream_operator()") diff --git a/tests/foo.h b/tests/foo.h index c9987d0..072febb 100644 --- a/tests/foo.h +++ b/tests/foo.h @@ -49,6 +49,11 @@ public: virtual ~Foo() { Foo::instance_count--; } }; +inline std::ostream & operator << (std::ostream &os, Foo const &foo) +{ + os << foo.get_datum (); + return os; +} class Zoo // -#- automatic_type_narrowing=True -#- diff --git a/tests/foomodulegen.py b/tests/foomodulegen.py index 6e92716..425684e 100755 --- a/tests/foomodulegen.py +++ b/tests/foomodulegen.py @@ -29,6 +29,7 @@ def my_module_gen(out_file): Foo.add_constructor([]) Foo.add_method('get_datum', ReturnValue.new('std::string'), []) Foo.add_method('is_initialized', ReturnValue.new('bool'), [], is_const=True) + Foo.add_output_stream_operator() Zoo = mod.add_class('Zoo', automatic_type_narrowing=True) Zoo.add_constructor([Parameter.new('std::string', 'datum')]) diff --git a/tests/footest.py b/tests/footest.py index 78c31ff..b9ab3b2 100644 --- a/tests/footest.py +++ b/tests/footest.py @@ -710,5 +710,10 @@ class TestFoo(unittest.TestCase): expected = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0] self.assertEqual(result, expected) + def test_output_stream(self): + f = foo.Foo("hello") + self.assertEqual(str(f), "hello") + + if __name__ == '__main__': unittest.main()