diff --git a/docs/advanced.rst b/docs/advanced.rst index 26046e1b4..aa53a1931 100644 --- a/docs/advanced.rst +++ b/docs/advanced.rst @@ -102,8 +102,9 @@ C++ side, or to perform other types of customization. .. seealso:: - The file :file:`example/example3.cpp` contains a complete example that - demonstrates how to work with overloaded operators in more detail. + The file :file:`example/example-operator-overloading.cpp` contains a + complete example that demonstrates how to work with overloaded operators in + more detail. Callbacks and passing anonymous functions ========================================= @@ -209,8 +210,9 @@ The following interactive session shows how to call them from Python. This functionality is very useful when generating bindings for callbacks in C++ libraries (e.g. GUI libraries, asynchronous networking libraries, etc.). - The file :file:`example/example5.cpp` contains a complete example that - demonstrates how to work with callbacks and anonymous functions in more detail. + The file :file:`example/example-callbacks.cpp` contains a complete example + that demonstrates how to work with callbacks and anonymous functions in + more detail. Overriding virtual functions in Python ====================================== @@ -347,9 +349,9 @@ Please take a look at the :ref:`macro_notes` before using this feature. .. seealso:: - The file :file:`example/example12.cpp` contains a complete example that - demonstrates how to override virtual functions using pybind11 in more - detail. + The file :file:`example/example-virtual-functions.cpp` contains a complete + example that demonstrates how to override virtual functions using pybind11 + in more detail. .. _macro_notes: @@ -433,8 +435,8 @@ out of the box with just the core :file:`pybind11/pybind11.h` header. .. seealso:: - The file :file:`example/example2.cpp` contains a complete example that - demonstrates how to pass STL data types in more detail. + The file :file:`example/example-python-types.cpp` contains a complete + example that demonstrates how to pass STL data types in more detail. Binding sequence data types, iterators, the slicing protocol, etc. ================================================================== @@ -443,10 +445,10 @@ Please refer to the supplemental example for details. .. seealso:: - The file :file:`example/example6.cpp` contains a complete example that - shows how to bind a sequence data type, including length queries - (``__len__``), iterators (``__iter__``), the slicing protocol and other - kinds of useful operations. + The file :file:`example/example-sequences-and-iterators.cpp` contains a + complete example that shows how to bind a sequence data type, including + length queries (``__len__``), iterators (``__iter__``), the slicing + protocol and other kinds of useful operations. Return value policies ===================== @@ -630,8 +632,8 @@ might be declared as follows: .. seealso:: - The file :file:`example/example13.cpp` contains a complete example that - demonstrates using :class:`keep_alive` in more detail. + The file :file:`example/example-keep-alive.cpp` contains a complete example + that demonstrates using :class:`keep_alive` in more detail. Implicit type conversions ========================= @@ -832,9 +834,9 @@ Please take a look at the :ref:`macro_notes` before using this feature. .. seealso:: - The file :file:`example/example8.cpp` contains a complete example that - demonstrates how to work with custom reference-counting holder types in - more detail. + The file :file:`example/example-smart-ptr.cpp` contains a complete example + that demonstrates how to work with custom reference-counting holder types + in more detail. .. _custom_constructors: @@ -939,7 +941,7 @@ a first shot at handling the exception). Inside the translator, ``std::rethrow_exception`` should be used within a try block to re-throw the exception. A catch clause can then use ``PyErr_SetString`` to set a Python exception as demonstrated -in :file:`example19.cpp``. +in :file:`example-custom-exceptions.cpp``. This example also demonstrates how to create custom exception types with ``py::exception``. @@ -1077,9 +1079,9 @@ Please take a look at the :ref:`macro_notes` before using this feature. .. seealso:: - The file :file:`example/example14.cpp` contains a complete example that - demonstrates how to create and expose opaque types using pybind11 in more - detail. + The file :file:`example/example-opaque-types.cpp` contains a complete + example that demonstrates how to create and expose opaque types using + pybind11 in more detail. .. _eigen: @@ -1249,8 +1251,8 @@ limitations), refer to the section on :ref:`eigen`. .. seealso:: - The file :file:`example/example7.cpp` contains a complete example that - demonstrates using the buffer protocol with pybind11 in more detail. + The file :file:`example/example-buffers.cpp` contains a complete example + that demonstrates using the buffer protocol with pybind11 in more detail. .. [#f2] http://docs.python.org/3/c-api/buffer.html @@ -1398,8 +1400,8 @@ simply using ``vectorize``). .. seealso:: - The file :file:`example/example10.cpp` contains a complete example that - demonstrates using :func:`vectorize` in more detail. + The file :file:`example/example-numpy-vectorize.cpp` contains a complete + example that demonstrates using :func:`vectorize` in more detail. Functions taking Python objects as arguments ============================================ @@ -1462,9 +1464,10 @@ with other parameters. .. seealso:: - The file :file:`example/example2.cpp` contains a complete example that - demonstrates passing native Python types in more detail. The file - :file:`example/example11.cpp` discusses usage of ``args`` and ``kwargs``. + The file :file:`example/example-python-types.cpp` contains a complete + example that demonstrates passing native Python types in more detail. The + file :file:`example/example-arg-keywords-and-defaults.cpp` discusses usage + of ``args`` and ``kwargs``. Default arguments revisited =========================== @@ -1537,11 +1540,11 @@ Such functions can also be created using pybind11: /// Binding code m.def("generic", &generic); -(See ``example/example11.cpp``). The class ``py::args`` derives from -``py::list`` and ``py::kwargs`` derives from ``py::dict`` Note that the -``kwargs`` argument is invalid if no keyword arguments were actually provided. -Please refer to the other examples for details on how to iterate over these, -and on how to cast their entries into C++ objects. +(See ``example/example-arg-keywords-and-defaults.cpp``). The class ``py::args`` +derives from ``py::list`` and ``py::kwargs`` derives from ``py::dict`` Note +that the ``kwargs`` argument is invalid if no keyword arguments were actually +provided. Please refer to the other examples for details on how to iterate +over these, and on how to cast their entries into C++ objects. Partitioning code over multiple extension modules ================================================= @@ -1682,8 +1685,9 @@ memory corruption and/or segmentation faults. .. seealso:: - The file :file:`example/example15.cpp` contains a complete example that - demonstrates how to pickle and unpickle types using pybind11 in more detail. + The file :file:`example/example-pickling.cpp` contains a complete example + that demonstrates how to pickle and unpickle types using pybind11 in more + detail. .. [#f3] http://docs.python.org/3/library/pickle.html#pickling-class-instances diff --git a/example/CMakeLists.txt b/example/CMakeLists.txt index 2d30f0811..69800f75b 100644 --- a/example/CMakeLists.txt +++ b/example/CMakeLists.txt @@ -7,25 +7,25 @@ if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) endif() set(PYBIND11_EXAMPLES - example1.cpp - example2.cpp - example3.cpp - example4.cpp - example5.cpp - example6.cpp - example7.cpp - example8.cpp - example9.cpp - example10.cpp - example11.cpp - example12.cpp - example13.cpp - example14.cpp - example15.cpp - example16.cpp - example17.cpp - example18.cpp - example19.cpp + example-methods-and-attributes.cpp + example-python-types.cpp + example-operator-overloading.cpp + example-constants-and-functions.cpp + example-callbacks.cpp + example-sequences-and-iterators.cpp + example-buffers.cpp + example-smart-ptr.cpp + example-modules.cpp + example-numpy-vectorize.cpp + example-arg-keywords-and-defaults.cpp + example-virtual-functions.cpp + example-keep-alive.cpp + example-opaque-types.cpp + example-pickling.cpp + example-inheritance.cpp + example-stl-binder-vector.cpp + example-eval.cpp + example-custom-exceptions.cpp issues.cpp ) diff --git a/example/example11.cpp b/example/example-arg-keywords-and-defaults.cpp similarity index 92% rename from example/example11.cpp rename to example/example-arg-keywords-and-defaults.cpp index 4b3c6d08b..4e620de52 100644 --- a/example/example11.cpp +++ b/example/example-arg-keywords-and-defaults.cpp @@ -1,5 +1,5 @@ /* - example/example11.cpp -- keyword arguments and default values + example/example-arg-keywords-and-defaults.cpp -- keyword arguments and default values Copyright (c) 2016 Wenzel Jakob @@ -40,7 +40,7 @@ void args_kwargs_function(py::args args, py::kwargs kwargs) { } } -void init_ex11(py::module &m) { +void init_ex_arg_keywords_and_defaults(py::module &m) { m.def("kw_func", &kw_func, py::arg("x"), py::arg("y")); m.def("kw_func2", &kw_func, py::arg("x") = 100, py::arg("y") = 200); m.def("kw_func3", [](const char *) { }, py::arg("data") = std::string("Hello world!")); diff --git a/example/example11.py b/example/example-arg-keywords-and-defaults.py similarity index 100% rename from example/example11.py rename to example/example-arg-keywords-and-defaults.py diff --git a/example/example11.ref b/example/example-arg-keywords-and-defaults.ref similarity index 100% rename from example/example11.ref rename to example/example-arg-keywords-and-defaults.ref diff --git a/example/example7.cpp b/example/example-buffers.cpp similarity index 97% rename from example/example7.cpp rename to example/example-buffers.cpp index 6aabf1c1c..709770b59 100644 --- a/example/example7.cpp +++ b/example/example-buffers.cpp @@ -1,5 +1,5 @@ /* - example/example7.cpp -- supporting Pythons' buffer protocol + example/example-buffers.cpp -- supporting Pythons' buffer protocol Copyright (c) 2016 Wenzel Jakob @@ -73,7 +73,7 @@ private: float *m_data; }; -void init_ex7(py::module &m) { +void init_ex_buffers(py::module &m) { py::class_ mtx(m, "Matrix"); mtx.def(py::init()) diff --git a/example/example7.py b/example/example-buffers.py similarity index 100% rename from example/example7.py rename to example/example-buffers.py diff --git a/example/example7.ref b/example/example-buffers.ref similarity index 100% rename from example/example7.ref rename to example/example-buffers.ref diff --git a/example/example5.cpp b/example/example-callbacks.cpp similarity index 66% rename from example/example5.cpp rename to example/example-callbacks.cpp index 3c144f220..a7a583e67 100644 --- a/example/example5.cpp +++ b/example/example-callbacks.cpp @@ -1,6 +1,5 @@ /* - example/example5.cpp -- inheritance, callbacks, acquiring and releasing the - global interpreter lock + example/example-callbacks.cpp -- callbacks Copyright (c) 2016 Wenzel Jakob @@ -12,36 +11,6 @@ #include -class Pet { -public: - Pet(const std::string &name, const std::string &species) - : m_name(name), m_species(species) {} - std::string name() const { return m_name; } - std::string species() const { return m_species; } -private: - std::string m_name; - std::string m_species; -}; - -class Dog : public Pet { -public: - Dog(const std::string &name) : Pet(name, "dog") {} - void bark() const { std::cout << "Woof!" << std::endl; } -}; - -class Rabbit : public Pet { -public: - Rabbit(const std::string &name) : Pet(name, "parrot") {} -}; - -void pet_print(const Pet &pet) { - std::cout << pet.name() + " is a " + pet.species() << std::endl; -} - -void dog_bark(const Dog &dog) { - dog.bark(); -} - bool test_callback1(py::object func) { func(); return false; @@ -88,24 +57,7 @@ void test_dummy_function(const std::function &f) { } } -void init_ex5(py::module &m) { - py::class_ pet_class(m, "Pet"); - pet_class - .def(py::init()) - .def("name", &Pet::name) - .def("species", &Pet::species); - - /* One way of declaring a subclass relationship: reference parent's class_ object */ - py::class_(m, "Dog", pet_class) - .def(py::init()); - - /* Another way of declaring a subclass relationship: reference parent's C++ type */ - py::class_(m, "Rabbit", py::base()) - .def(py::init()); - - m.def("pet_print", pet_print); - m.def("dog_bark", dog_bark); - +void init_ex_callbacks(py::module &m) { m.def("test_callback1", &test_callback1); m.def("test_callback2", &test_callback2); m.def("test_callback3", &test_callback3); diff --git a/example/example5.py b/example/example-callbacks.py similarity index 100% rename from example/example5.py rename to example/example-callbacks.py diff --git a/example/example5.ref b/example/example-callbacks.ref similarity index 100% rename from example/example5.ref rename to example/example-callbacks.ref diff --git a/example/example4.cpp b/example/example-constants-and-functions.cpp similarity index 71% rename from example/example4.cpp rename to example/example-constants-and-functions.cpp index 7e17864e0..b71856cbe 100644 --- a/example/example4.cpp +++ b/example/example-constants-and-functions.cpp @@ -1,5 +1,5 @@ /* - example/example4.cpp -- global constants and functions, enumerations, raw byte strings + example/example-constants-and-functions.cpp -- global constants and functions, enumerations, raw byte strings Copyright (c) 2016 Wenzel Jakob @@ -14,7 +14,7 @@ enum EMyEnumeration { ESecondEntry }; -class Example4 { +class ExampleWithEnum { public: enum EMode { EFirstMode = 1, @@ -22,7 +22,7 @@ public: }; static EMode test_function(EMode mode) { - std::cout << "Example4::test_function(enum=" << mode << ")" << std::endl; + std::cout << "ExampleWithEnum::test_function(enum=" << mode << ")" << std::endl; return mode; } }; @@ -52,7 +52,7 @@ void print_bytes(py::bytes bytes) { std::cout << "bytes[" << i << "]=" << (int) value[i] << std::endl; } -void init_ex4(py::module &m) { +void init_ex_constants_and_functions(py::module &m) { m.def("test_function", &test_function1); m.def("test_function", &test_function2); m.def("test_function", &test_function3); @@ -63,11 +63,11 @@ void init_ex4(py::module &m) { .value("ESecondEntry", ESecondEntry) .export_values(); - py::class_ ex4_class(m, "Example4"); - ex4_class.def_static("test_function", &Example4::test_function); - py::enum_(ex4_class, "EMode") - .value("EFirstMode", Example4::EFirstMode) - .value("ESecondMode", Example4::ESecondMode) + py::class_ exenum_class(m, "ExampleWithEnum"); + exenum_class.def_static("test_function", &ExampleWithEnum::test_function); + py::enum_(exenum_class, "EMode") + .value("EFirstMode", ExampleWithEnum::EFirstMode) + .value("ESecondMode", ExampleWithEnum::ESecondMode) .export_values(); m.def("return_bytes", &return_bytes); diff --git a/example/example-constants-and-functions.py b/example/example-constants-and-functions.py new file mode 100755 index 000000000..607450f92 --- /dev/null +++ b/example/example-constants-and-functions.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python +from __future__ import print_function +import sys +sys.path.append('.') + +from example import test_function +from example import some_constant +from example import EMyEnumeration +from example import EFirstEntry +from example import ExampleWithEnum +from example import return_bytes +from example import print_bytes + +print(EMyEnumeration) +print(EMyEnumeration.EFirstEntry) +print(EMyEnumeration.ESecondEntry) +print(EFirstEntry) + +print(test_function()) +print(test_function(7)) +print(test_function(EMyEnumeration.EFirstEntry)) +print(test_function(EMyEnumeration.ESecondEntry)) +print("enum->integer = %i" % int(EMyEnumeration.ESecondEntry)) +print("integer->enum = %s" % str(EMyEnumeration(2))) + +print("A constant = " + str(some_constant)) + +print(ExampleWithEnum.EMode) +print(ExampleWithEnum.EMode.EFirstMode) +print(ExampleWithEnum.EFirstMode) +ExampleWithEnum.test_function(ExampleWithEnum.EFirstMode) + +print("Equality test 1: " + str( + ExampleWithEnum.test_function(ExampleWithEnum.EFirstMode) == + ExampleWithEnum.test_function(ExampleWithEnum.EFirstMode))) + +print("Inequality test 1: " + str( + ExampleWithEnum.test_function(ExampleWithEnum.EFirstMode) != + ExampleWithEnum.test_function(ExampleWithEnum.EFirstMode))) + +print("Equality test 2: " + str( + ExampleWithEnum.test_function(ExampleWithEnum.EFirstMode) == + ExampleWithEnum.test_function(ExampleWithEnum.ESecondMode))) + +print("Inequality test 2: " + str( + ExampleWithEnum.test_function(ExampleWithEnum.EFirstMode) != + ExampleWithEnum.test_function(ExampleWithEnum.ESecondMode))) + +x = { + ExampleWithEnum.test_function(ExampleWithEnum.EFirstMode): 1, + ExampleWithEnum.test_function(ExampleWithEnum.ESecondMode): 2 +} + +x[ExampleWithEnum.test_function(ExampleWithEnum.EFirstMode)] = 3 +x[ExampleWithEnum.test_function(ExampleWithEnum.ESecondMode)] = 4 +print("Hashing test = " + str(x)) + +print_bytes(return_bytes()) diff --git a/example/example4.ref b/example/example-constants-and-functions.ref similarity index 51% rename from example/example4.ref rename to example/example-constants-and-functions.ref index a21f62c93..d2e1731aa 100644 --- a/example/example4.ref +++ b/example/example-constants-and-functions.ref @@ -16,23 +16,23 @@ A constant = 14 EMode.EFirstMode EMode.EFirstMode -Example4::test_function(enum=1) -Example4::test_function(enum=1) -Example4::test_function(enum=1) +ExampleWithEnum::test_function(enum=1) +ExampleWithEnum::test_function(enum=1) +ExampleWithEnum::test_function(enum=1) Equality test 1: True -Example4::test_function(enum=1) -Example4::test_function(enum=1) +ExampleWithEnum::test_function(enum=1) +ExampleWithEnum::test_function(enum=1) Inequality test 1: False -Example4::test_function(enum=1) -Example4::test_function(enum=2) +ExampleWithEnum::test_function(enum=1) +ExampleWithEnum::test_function(enum=2) Equality test 2: False -Example4::test_function(enum=1) -Example4::test_function(enum=2) +ExampleWithEnum::test_function(enum=1) +ExampleWithEnum::test_function(enum=2) Inequality test 2: True -Example4::test_function(enum=1) -Example4::test_function(enum=2) -Example4::test_function(enum=1) -Example4::test_function(enum=2) +ExampleWithEnum::test_function(enum=1) +ExampleWithEnum::test_function(enum=2) +ExampleWithEnum::test_function(enum=1) +ExampleWithEnum::test_function(enum=2) Hashing test = {EMode.EFirstMode: 3, EMode.ESecondMode: 4} bytes[0]=1 bytes[1]=0 diff --git a/example/example19.cpp b/example/example-custom-exceptions.cpp similarity index 96% rename from example/example19.cpp rename to example/example-custom-exceptions.cpp index e382225e2..41d51d84f 100644 --- a/example/example19.cpp +++ b/example/example-custom-exceptions.cpp @@ -1,5 +1,5 @@ /* - example/example19.cpp -- exception translation + example/example-custom-exceptions.cpp -- exception translation Copyright (c) 2016 Pim Schellart @@ -66,7 +66,7 @@ void throws_logic_error() { throw std::logic_error("this error should fall through to the standard handler"); } -void init_ex19(py::module &m) { +void init_ex_custom_exceptions(py::module &m) { // make a new custom exception and use it as a translation target static py::exception ex(m, "MyException"); py::register_exception_translator([](std::exception_ptr p) { diff --git a/example/example19.py b/example/example-custom-exceptions.py similarity index 100% rename from example/example19.py rename to example/example-custom-exceptions.py diff --git a/example/example19.ref b/example/example-custom-exceptions.ref similarity index 100% rename from example/example19.ref rename to example/example-custom-exceptions.ref diff --git a/example/example18.cpp b/example/example-eval.cpp similarity index 87% rename from example/example18.cpp rename to example/example-eval.cpp index 8fdab8157..f6de893d4 100644 --- a/example/example18.cpp +++ b/example/example-eval.cpp @@ -1,5 +1,5 @@ /* - example/example18.cpp -- Usage of eval() and eval_file() + example/example-eval.cpp -- Usage of eval() and eval_file() Copyright (c) 2016 Klemens D. Morgenstern @@ -11,7 +11,7 @@ #include #include "example.h" -void example18() { +void example_eval() { py::module main_module = py::module::import("__main__"); py::object main_namespace = main_module.attr("__dict__"); @@ -59,9 +59,9 @@ void example18() { main_module.def("call_test2", [&](int value) {val_out = value;}); try { - result = py::eval_file("example18_call.py", main_namespace); + result = py::eval_file("example-eval_call.py", main_namespace); } catch (...) { - result = py::eval_file("example/example18_call.py", main_namespace); + result = py::eval_file("example/example-eval_call.py", main_namespace); } if (val_out == 42 && result == py::none()) @@ -97,6 +97,6 @@ void example18() { cout << "eval_file failure test failed" << endl; } -void init_ex18(py::module & m) { - m.def("example18", &example18); +void init_ex_eval(py::module & m) { + m.def("example_eval", &example_eval); } diff --git a/example/example-eval.py b/example/example-eval.py new file mode 100644 index 000000000..eec10c3b0 --- /dev/null +++ b/example/example-eval.py @@ -0,0 +1,5 @@ +from example import example_eval + +example_eval() + + diff --git a/example/example18.ref b/example/example-eval.ref similarity index 100% rename from example/example18.ref rename to example/example-eval.ref diff --git a/example/example18_call.py b/example/example-eval_call.py similarity index 100% rename from example/example18_call.py rename to example/example-eval_call.py diff --git a/example/example-inheritance.cpp b/example/example-inheritance.cpp new file mode 100644 index 000000000..082978b4e --- /dev/null +++ b/example/example-inheritance.cpp @@ -0,0 +1,72 @@ +/* + example/example-inheritance.cpp -- inheritance, automatic upcasting for polymorphic types + + Copyright (c) 2016 Wenzel Jakob + + All rights reserved. Use of this source code is governed by a + BSD-style license that can be found in the LICENSE file. +*/ + +#include "example.h" + +class Pet { +public: + Pet(const std::string &name, const std::string &species) + : m_name(name), m_species(species) {} + std::string name() const { return m_name; } + std::string species() const { return m_species; } +private: + std::string m_name; + std::string m_species; +}; + +class Dog : public Pet { +public: + Dog(const std::string &name) : Pet(name, "dog") {} + void bark() const { std::cout << "Woof!" << std::endl; } +}; + +class Rabbit : public Pet { +public: + Rabbit(const std::string &name) : Pet(name, "parrot") {} +}; + +void pet_print(const Pet &pet) { + std::cout << pet.name() + " is a " + pet.species() << std::endl; +} + +void dog_bark(const Dog &dog) { + dog.bark(); +} + + +struct BaseClass { virtual ~BaseClass() {} }; +struct DerivedClass1 : BaseClass { }; +struct DerivedClass2 : BaseClass { }; + +void init_ex_inheritance(py::module &m) { + py::class_ pet_class(m, "Pet"); + pet_class + .def(py::init()) + .def("name", &Pet::name) + .def("species", &Pet::species); + + /* One way of declaring a subclass relationship: reference parent's class_ object */ + py::class_(m, "Dog", pet_class) + .def(py::init()); + + /* Another way of declaring a subclass relationship: reference parent's C++ type */ + py::class_(m, "Rabbit", py::base()) + .def(py::init()); + + m.def("pet_print", pet_print); + m.def("dog_bark", dog_bark); + + py::class_(m, "BaseClass").def(py::init<>()); + py::class_(m, "DerivedClass1").def(py::init<>()); + py::class_(m, "DerivedClass2").def(py::init<>()); + + m.def("return_class_1", []() -> BaseClass* { return new DerivedClass1(); }); + m.def("return_class_2", []() -> BaseClass* { return new DerivedClass2(); }); + m.def("return_none", []() -> BaseClass* { return nullptr; }); +} diff --git a/example/example16.py b/example/example-inheritance.py similarity index 100% rename from example/example16.py rename to example/example-inheritance.py diff --git a/example/example16.ref b/example/example-inheritance.ref similarity index 100% rename from example/example16.ref rename to example/example-inheritance.ref diff --git a/example/example13.cpp b/example/example-keep-alive.cpp similarity index 90% rename from example/example13.cpp rename to example/example-keep-alive.cpp index 6c1b8765d..c099aa81f 100644 --- a/example/example13.cpp +++ b/example/example-keep-alive.cpp @@ -1,5 +1,5 @@ /* - example/example13.cpp -- keep_alive modifier (pybind11's version + example/example-keep-alive.cpp -- keep_alive modifier (pybind11's version of Boost.Python's with_custodian_and_ward / with_custodian_and_ward_postcall) Copyright (c) 2016 Wenzel Jakob @@ -24,7 +24,7 @@ public: Child *returnChild() { return new Child(); } }; -void init_ex13(py::module &m) { +void init_ex_keep_alive(py::module &m) { py::class_(m, "Parent") .def(py::init<>()) .def("addChild", &Parent::addChild) diff --git a/example/example13.py b/example/example-keep-alive.py similarity index 100% rename from example/example13.py rename to example/example-keep-alive.py diff --git a/example/example13.ref b/example/example-keep-alive.ref similarity index 100% rename from example/example13.ref rename to example/example-keep-alive.ref diff --git a/example/example-methods-and-attributes.cpp b/example/example-methods-and-attributes.cpp new file mode 100644 index 000000000..800078cf5 --- /dev/null +++ b/example/example-methods-and-attributes.cpp @@ -0,0 +1,92 @@ +/* + example/example-methods-and-attributes.cpp -- constructors, deconstructors, attribute access, + __str__, argument and return value conventions + + Copyright (c) 2016 Wenzel Jakob + + All rights reserved. Use of this source code is governed by a + BSD-style license that can be found in the LICENSE file. +*/ + +#include "example.h" + +class ExampleMandA { +public: + ExampleMandA() { + cout << "Called ExampleMandA default constructor.." << endl; + } + ExampleMandA(int value) : value(value) { + cout << "Called ExampleMandA constructor with value " << value << ".." << endl; + } + ExampleMandA(const ExampleMandA &e) : value(e.value) { + cout << "Called ExampleMandA copy constructor with value " << value << ".." << endl; + } + ExampleMandA(ExampleMandA &&e) : value(e.value) { + cout << "Called ExampleMandA move constructor with value " << value << ".." << endl; + e.value = 0; + } + ~ExampleMandA() { + cout << "Called ExampleMandA destructor (" << value << ")" << endl; + } + std::string toString() { + return "ExampleMandA[value=" + std::to_string(value) + "]"; + } + + void operator=(const ExampleMandA &e) { cout << "Assignment operator" << endl; value = e.value; } + void operator=(ExampleMandA &&e) { cout << "Move assignment operator" << endl; value = e.value; e.value = 0;} + + void add1(ExampleMandA other) { value += other.value; } // passing by value + void add2(ExampleMandA &other) { value += other.value; } // passing by reference + void add3(const ExampleMandA &other) { value += other.value; } // passing by const reference + void add4(ExampleMandA *other) { value += other->value; } // passing by pointer + void add5(const ExampleMandA *other) { value += other->value; } // passing by const pointer + + void add6(int other) { value += other; } // passing by value + void add7(int &other) { value += other; } // passing by reference + void add8(const int &other) { value += other; } // passing by const reference + void add9(int *other) { value += *other; } // passing by pointer + void add10(const int *other) { value += *other; } // passing by const pointer + + ExampleMandA self1() { return *this; } // return by value + ExampleMandA &self2() { return *this; } // return by reference + const ExampleMandA &self3() { return *this; } // return by const reference + ExampleMandA *self4() { return this; } // return by pointer + const ExampleMandA *self5() { return this; } // return by const pointer + + int internal1() { return value; } // return by value + int &internal2() { return value; } // return by reference + const int &internal3() { return value; } // return by const reference + int *internal4() { return &value; } // return by pointer + const int *internal5() { return &value; } // return by const pointer + + int value = 0; +}; + +void init_ex_methods_and_attributes(py::module &m) { + py::class_(m, "ExampleMandA") + .def(py::init<>()) + .def(py::init()) + .def(py::init()) + .def("add1", &ExampleMandA::add1) + .def("add2", &ExampleMandA::add2) + .def("add3", &ExampleMandA::add3) + .def("add4", &ExampleMandA::add4) + .def("add5", &ExampleMandA::add5) + .def("add6", &ExampleMandA::add6) + .def("add7", &ExampleMandA::add7) + .def("add8", &ExampleMandA::add8) + .def("add9", &ExampleMandA::add9) + .def("add10", &ExampleMandA::add10) + .def("self1", &ExampleMandA::self1) + .def("self2", &ExampleMandA::self2) + .def("self3", &ExampleMandA::self3) + .def("self4", &ExampleMandA::self4) + .def("self5", &ExampleMandA::self5) + .def("internal1", &ExampleMandA::internal1) + .def("internal2", &ExampleMandA::internal2) + .def("internal3", &ExampleMandA::internal3) + .def("internal4", &ExampleMandA::internal4) + .def("internal5", &ExampleMandA::internal5) + .def("__str__", &ExampleMandA::toString) + .def_readwrite("value", &ExampleMandA::value); +} diff --git a/example/example1.py b/example/example-methods-and-attributes.py similarity index 89% rename from example/example1.py rename to example/example-methods-and-attributes.py index f89b662d8..229e1c987 100755 --- a/example/example1.py +++ b/example/example-methods-and-attributes.py @@ -3,10 +3,10 @@ from __future__ import print_function import sys sys.path.append('.') -from example import Example1 +from example import ExampleMandA -instance1 = Example1() -instance2 = Example1(32) +instance1 = ExampleMandA() +instance2 = ExampleMandA(32) instance1.add1(instance2) instance1.add2(instance2) instance1.add3(instance2) diff --git a/example/example-methods-and-attributes.ref b/example/example-methods-and-attributes.ref new file mode 100644 index 000000000..95277903d --- /dev/null +++ b/example/example-methods-and-attributes.ref @@ -0,0 +1,26 @@ +Called ExampleMandA default constructor.. +Called ExampleMandA constructor with value 32.. +Called ExampleMandA copy constructor with value 32.. +Called ExampleMandA copy constructor with value 32.. +Called ExampleMandA destructor (32) +Called ExampleMandA destructor (32) +Instance 1: ExampleMandA[value=320] +Instance 2: ExampleMandA[value=32] +Called ExampleMandA copy constructor with value 320.. +Called ExampleMandA move constructor with value 320.. +Called ExampleMandA destructor (0) +ExampleMandA[value=320] +Called ExampleMandA destructor (320) +ExampleMandA[value=320] +ExampleMandA[value=320] +ExampleMandA[value=320] +ExampleMandA[value=320] +320 +320 +320 +320 +320 +Instance 1, direct access = 320 +Instance 1: ExampleMandA[value=100] +Called ExampleMandA destructor (32) +Called ExampleMandA destructor (100) diff --git a/example/example9.cpp b/example/example-modules.cpp similarity index 93% rename from example/example9.cpp rename to example/example-modules.cpp index ca75ecc79..fdaf72ece 100644 --- a/example/example9.cpp +++ b/example/example-modules.cpp @@ -1,5 +1,5 @@ /* - example/example9.cpp -- nested modules, importing modules, and + example/example-modules.cpp -- nested modules, importing modules, and internal references Copyright (c) 2016 Wenzel Jakob @@ -36,7 +36,7 @@ public: A a2{2}; }; -void init_ex9(py::module &m) { +void init_ex_modules(py::module &m) { py::module m_sub = m.def_submodule("submodule"); m_sub.def("submodule_func", &submodule_func); diff --git a/example/example9.py b/example/example-modules.py similarity index 100% rename from example/example9.py rename to example/example-modules.py diff --git a/example/example9.ref b/example/example-modules.ref similarity index 100% rename from example/example9.ref rename to example/example-modules.ref diff --git a/example/example10.cpp b/example/example-numpy-vectorize.cpp similarity index 92% rename from example/example10.cpp rename to example/example-numpy-vectorize.cpp index 06528c2f0..8780d28ff 100644 --- a/example/example10.cpp +++ b/example/example-numpy-vectorize.cpp @@ -1,5 +1,5 @@ /* - example/example10.cpp -- auto-vectorize functions over NumPy array + example/example-numpy-vectorize.cpp -- auto-vectorize functions over NumPy array arguments Copyright (c) 2016 Wenzel Jakob @@ -20,7 +20,7 @@ std::complex my_func3(std::complex c) { return c * std::complex(2.f); } -void init_ex10(py::module &m) { +void init_ex_numpy_vectorize(py::module &m) { // Vectorize all arguments of a function (though non-vector arguments are also allowed) m.def("vectorized_func", py::vectorize(my_func)); diff --git a/example/example10.py b/example/example-numpy-vectorize.py similarity index 100% rename from example/example10.py rename to example/example-numpy-vectorize.py diff --git a/example/example10.ref b/example/example-numpy-vectorize.ref similarity index 100% rename from example/example10.ref rename to example/example-numpy-vectorize.ref diff --git a/example/example14.cpp b/example/example-opaque-types.cpp similarity index 94% rename from example/example14.cpp rename to example/example-opaque-types.cpp index ad67fe419..2c24f3546 100644 --- a/example/example14.cpp +++ b/example/example-opaque-types.cpp @@ -1,5 +1,5 @@ /* - example/example14.cpp -- opaque types, passing void pointers + example/example-opaque-types.cpp -- opaque types, passing void pointers Copyright (c) 2016 Wenzel Jakob @@ -21,7 +21,7 @@ public: /* IMPORTANT: Disable internal pybind11 translation mechanisms for STL data structures */ PYBIND11_MAKE_OPAQUE(StringList); -void init_ex14(py::module &m) { +void init_ex_opaque_types(py::module &m) { py::class_(m, "StringList") .def(py::init<>()) .def("pop_back", &StringList::pop_back) diff --git a/example/example14.py b/example/example-opaque-types.py similarity index 90% rename from example/example14.py rename to example/example-opaque-types.py index c653e0cea..8fd09f6cd 100644 --- a/example/example14.py +++ b/example/example-opaque-types.py @@ -8,7 +8,7 @@ from example import ClassWithSTLVecProperty from example import return_void_ptr, print_void_ptr from example import return_null_str, print_null_str from example import return_unique_ptr -from example import Example1 +from example import ExampleMandA ##### @@ -33,7 +33,7 @@ print_opaque_list(cvp.stringList) ##### print_void_ptr(return_void_ptr()) -print_void_ptr(Example1()) # Should also work for other C++ types +print_void_ptr(ExampleMandA()) # Should also work for other C++ types try: print_void_ptr([1, 2, 3]) # This should not work diff --git a/example/example14.ref b/example/example-opaque-types.ref similarity index 86% rename from example/example14.ref rename to example/example-opaque-types.ref index 44e682098..a6672fde0 100644 --- a/example/example14.ref +++ b/example/example-opaque-types.ref @@ -6,9 +6,9 @@ Opaque list: [Element 1] Opaque list: [] Opaque list: [Element 1, Element 3] Got void ptr : 0x1234 -Called Example1 default constructor.. +Called ExampleMandA default constructor.. Got void ptr : 0x7f9ba0f3c430 -Called Example1 destructor (0) +Called ExampleMandA destructor (0) Caught expected exception: Incompatible function arguments. The following argument types are supported: 1. (capsule) -> NoneType Invoked with: [1, 2, 3] diff --git a/example/example3.cpp b/example/example-operator-overloading.cpp similarity index 95% rename from example/example3.cpp rename to example/example-operator-overloading.cpp index af956b13e..ff5e658a9 100644 --- a/example/example3.cpp +++ b/example/example-operator-overloading.cpp @@ -1,5 +1,5 @@ /* - example/example3.cpp -- operator overloading + example/example-operator-overloading.cpp -- operator overloading Copyright (c) 2016 Wenzel Jakob @@ -52,7 +52,7 @@ private: }; -void init_ex3(py::module &m) { +void init_ex_operator_overloading(py::module &m) { py::class_(m, "Vector2") .def(py::init()) .def(py::self + py::self) diff --git a/example/example3.py b/example/example-operator-overloading.py similarity index 100% rename from example/example3.py rename to example/example-operator-overloading.py diff --git a/example/example3.ref b/example/example-operator-overloading.ref similarity index 100% rename from example/example3.ref rename to example/example-operator-overloading.ref diff --git a/example/example15.cpp b/example/example-pickling.cpp similarity index 95% rename from example/example15.cpp rename to example/example-pickling.cpp index acdd36823..b89f78a3e 100644 --- a/example/example15.cpp +++ b/example/example-pickling.cpp @@ -1,5 +1,5 @@ /* - example/example15.cpp -- pickle support + example/example-pickling.cpp -- pickle support Copyright (c) 2016 Wenzel Jakob @@ -24,7 +24,7 @@ private: int m_extra2 = 0; }; -void init_ex15(py::module &m) { +void init_ex_pickling(py::module &m) { py::class_(m, "Pickleable") .def(py::init()) .def("value", &Pickleable::value) diff --git a/example/example15.py b/example/example-pickling.py similarity index 100% rename from example/example15.py rename to example/example-pickling.py diff --git a/example/example15.ref b/example/example-pickling.ref similarity index 100% rename from example/example15.ref rename to example/example-pickling.ref diff --git a/example/example2.cpp b/example/example-python-types.cpp similarity index 65% rename from example/example2.cpp rename to example/example-python-types.cpp index 4b15823f2..976583577 100644 --- a/example/example2.cpp +++ b/example/example-python-types.cpp @@ -1,5 +1,5 @@ /* - example/example2.cpp2 -- singleton design pattern, static functions and + example/example-python-types.cpp2 -- singleton design pattern, static functions and variables, passing and interacting with Python types Copyright (c) 2016 Wenzel Jakob @@ -16,13 +16,13 @@ # include #endif -class Example2 { +class ExamplePythonTypes { public: - static Example2 *new_instance() { - return new Example2(); + static ExamplePythonTypes *new_instance() { + return new ExamplePythonTypes(); } - ~Example2() { - std::cout << "Destructing Example2" << std::endl; + ~ExamplePythonTypes() { + std::cout << "Destructing ExamplePythonTypes" << std::endl; } /* Create and return a Python dictionary */ @@ -142,31 +142,31 @@ public: static const int value2; }; -int Example2::value = 0; -const int Example2::value2 = 5; +int ExamplePythonTypes::value = 0; +const int ExamplePythonTypes::value2 = 5; -void init_ex2(py::module &m) { +void init_ex_python_types(py::module &m) { /* No constructor is explicitly defined below. An exception is raised when trying to construct it directly from Python */ - py::class_(m, "Example2", "Example 2 documentation") - .def("get_dict", &Example2::get_dict, "Return a Python dictionary") - .def("get_dict_2", &Example2::get_dict_2, "Return a C++ dictionary") - .def("get_list", &Example2::get_list, "Return a Python list") - .def("get_list_2", &Example2::get_list_2, "Return a C++ list") - .def("get_set", &Example2::get_set, "Return a Python set") - .def("get_set2", &Example2::get_set_2, "Return a C++ set") - .def("get_array", &Example2::get_array, "Return a C++ array") - .def("print_dict", &Example2::print_dict, "Print entries of a Python dictionary") - .def("print_dict_2", &Example2::print_dict_2, "Print entries of a C++ dictionary") - .def("print_set", &Example2::print_set, "Print entries of a Python set") - .def("print_set_2", &Example2::print_set_2, "Print entries of a C++ set") - .def("print_list", &Example2::print_list, "Print entries of a Python list") - .def("print_list_2", &Example2::print_list_2, "Print entries of a C++ list") - .def("print_array", &Example2::print_array, "Print entries of a C++ array") - .def("pair_passthrough", &Example2::pair_passthrough, "Return a pair in reversed order") - .def("tuple_passthrough", &Example2::tuple_passthrough, "Return a triple in reversed order") - .def("throw_exception", &Example2::throw_exception, "Throw an exception") - .def_static("new_instance", &Example2::new_instance, "Return an instance") - .def_readwrite_static("value", &Example2::value, "Static value member") - .def_readonly_static("value2", &Example2::value2, "Static value member (readonly)"); + py::class_(m, "ExamplePythonTypes", "Example 2 documentation") + .def("get_dict", &ExamplePythonTypes::get_dict, "Return a Python dictionary") + .def("get_dict_2", &ExamplePythonTypes::get_dict_2, "Return a C++ dictionary") + .def("get_list", &ExamplePythonTypes::get_list, "Return a Python list") + .def("get_list_2", &ExamplePythonTypes::get_list_2, "Return a C++ list") + .def("get_set", &ExamplePythonTypes::get_set, "Return a Python set") + .def("get_set2", &ExamplePythonTypes::get_set_2, "Return a C++ set") + .def("get_array", &ExamplePythonTypes::get_array, "Return a C++ array") + .def("print_dict", &ExamplePythonTypes::print_dict, "Print entries of a Python dictionary") + .def("print_dict_2", &ExamplePythonTypes::print_dict_2, "Print entries of a C++ dictionary") + .def("print_set", &ExamplePythonTypes::print_set, "Print entries of a Python set") + .def("print_set_2", &ExamplePythonTypes::print_set_2, "Print entries of a C++ set") + .def("print_list", &ExamplePythonTypes::print_list, "Print entries of a Python list") + .def("print_list_2", &ExamplePythonTypes::print_list_2, "Print entries of a C++ list") + .def("print_array", &ExamplePythonTypes::print_array, "Print entries of a C++ array") + .def("pair_passthrough", &ExamplePythonTypes::pair_passthrough, "Return a pair in reversed order") + .def("tuple_passthrough", &ExamplePythonTypes::tuple_passthrough, "Return a triple in reversed order") + .def("throw_exception", &ExamplePythonTypes::throw_exception, "Throw an exception") + .def_static("new_instance", &ExamplePythonTypes::new_instance, "Return an instance") + .def_readwrite_static("value", &ExamplePythonTypes::value, "Static value member") + .def_readonly_static("value2", &ExamplePythonTypes::value2, "Static value member (readonly)"); } diff --git a/example/example2.py b/example/example-python-types.py similarity index 62% rename from example/example2.py rename to example/example-python-types.py index d335acc3d..df5a244b9 100755 --- a/example/example2.py +++ b/example/example-python-types.py @@ -4,23 +4,23 @@ import sys, pydoc sys.path.append('.') import example -from example import Example2 +from example import ExamplePythonTypes -Example2.value = 15 -print(Example2.value) -print(Example2.value2) +ExamplePythonTypes.value = 15 +print(ExamplePythonTypes.value) +print(ExamplePythonTypes.value2) try: - Example2() + ExamplePythonTypes() except Exception as e: print(e) try: - Example2.value2 = 15 + ExamplePythonTypes.value2 = 15 except Exception as e: print(e) -instance = Example2.new_instance() +instance = ExamplePythonTypes.new_instance() dict_result = instance.get_dict() dict_result['key2'] = 'value2' @@ -58,10 +58,10 @@ except Exception as e: print(instance.pair_passthrough((True, "test"))) print(instance.tuple_passthrough((True, "test", 5))) -print(pydoc.render_doc(Example2, "Help on %s")) +print(pydoc.render_doc(ExamplePythonTypes, "Help on %s")) print("__name__(example) = %s" % example.__name__) -print("__name__(example.Example2) = %s" % Example2.__name__) -print("__module__(example.Example2) = %s" % Example2.__module__) -print("__name__(example.Example2.get_set) = %s" % Example2.get_set.__name__) -print("__module__(example.Example2.get_set) = %s" % Example2.get_set.__module__) +print("__name__(example.ExamplePythonTypes) = %s" % ExamplePythonTypes.__name__) +print("__module__(example.ExamplePythonTypes) = %s" % ExamplePythonTypes.__module__) +print("__name__(example.ExamplePythonTypes.get_set) = %s" % ExamplePythonTypes.get_set.__name__) +print("__module__(example.ExamplePythonTypes.get_set) = %s" % ExamplePythonTypes.get_set.__module__) diff --git a/example/example2.ref b/example/example-python-types.ref similarity index 60% rename from example/example2.ref rename to example/example-python-types.ref index fd6c83dda..2a0237c57 100644 --- a/example/example2.ref +++ b/example/example-python-types.ref @@ -1,6 +1,6 @@ 15 5 -example.Example2: No constructor defined! +example.ExamplePythonTypes: No constructor defined! can't set attribute key: key2, value=value2 key: key, value=value @@ -23,9 +23,9 @@ array item 1: array entry 2 This exception was intentionally thrown. (u'test', True) (5L, u'test', True) -Help on class Example2 in module example +Help on class ExamplePythonTypes in module example -class EExxaammppllee22(__builtin__.object) +class EExxaammpplleePPyytthhoonnTTyyppeess(__builtin__.object) | Example 2 documentation | | Methods defined here: @@ -34,104 +34,104 @@ class EExxaammppllee22(__builtin__.object) | x.__init__(...) initializes x; see help(type(x)) for signature | | ggeett__aarrrraayy(...) - | Signature : (example.Example2) -> list[2] + | Signature : (example.ExamplePythonTypes) -> list[2] | | Return a C++ array | | ggeett__ddiicctt(...) - | Signature : (example.Example2) -> dict + | Signature : (example.ExamplePythonTypes) -> dict | | Return a Python dictionary | | ggeett__ddiicctt__22(...) - | Signature : (example.Example2) -> dict + | Signature : (example.ExamplePythonTypes) -> dict | | Return a C++ dictionary | | ggeett__lliisstt(...) - | Signature : (example.Example2) -> list + | Signature : (example.ExamplePythonTypes) -> list | | Return a Python list | | ggeett__lliisstt__22(...) - | Signature : (example.Example2) -> list + | Signature : (example.ExamplePythonTypes) -> list | | Return a C++ list | | ggeett__sseett(...) - | Signature : (example.Example2) -> set + | Signature : (example.ExamplePythonTypes) -> set | | Return a Python set | | ggeett__sseett22(...) - | Signature : (example.Example2) -> set + | Signature : (example.ExamplePythonTypes) -> set | | Return a C++ set | | ppaaiirr__ppaasssstthhrroouugghh(...) - | Signature : (example.Example2, (bool, unicode)) -> (unicode, bool) + | Signature : (example.ExamplePythonTypes, (bool, unicode)) -> (unicode, bool) | | Return a pair in reversed order | | pprriinntt__aarrrraayy(...) - | Signature : (example.Example2, list[2]) -> NoneType + | Signature : (example.ExamplePythonTypes, list[2]) -> NoneType | | Print entries of a C++ array | | pprriinntt__ddiicctt(...) - | Signature : (example.Example2, dict) -> NoneType + | Signature : (example.ExamplePythonTypes, dict) -> NoneType | | Print entries of a Python dictionary | | pprriinntt__ddiicctt__22(...) - | Signature : (example.Example2, dict) -> NoneType + | Signature : (example.ExamplePythonTypes, dict) -> NoneType | | Print entries of a C++ dictionary | | pprriinntt__lliisstt(...) - | Signature : (example.Example2, list) -> NoneType + | Signature : (example.ExamplePythonTypes, list) -> NoneType | | Print entries of a Python list | | pprriinntt__lliisstt__22(...) - | Signature : (example.Example2, list) -> NoneType + | Signature : (example.ExamplePythonTypes, list) -> NoneType | | Print entries of a C++ list | | pprriinntt__sseett(...) - | Signature : (example.Example2, set) -> NoneType + | Signature : (example.ExamplePythonTypes, set) -> NoneType | | Print entries of a Python set | | pprriinntt__sseett__22(...) - | Signature : (example.Example2, set) -> NoneType + | Signature : (example.ExamplePythonTypes, set) -> NoneType | | Print entries of a C++ set | | tthhrrooww__eexxcceeppttiioonn(...) - | Signature : (example.Example2) -> NoneType + | Signature : (example.ExamplePythonTypes) -> NoneType | | Throw an exception | | ttuuppllee__ppaasssstthhrroouugghh(...) - | Signature : (example.Example2, (bool, unicode, int)) -> (int, unicode, bool) + | Signature : (example.ExamplePythonTypes, (bool, unicode, int)) -> (int, unicode, bool) | | Return a triple in reversed order | | ---------------------------------------------------------------------- | Data and other attributes defined here: | - | ____nneeww____ = + | ____nneeww____ = | T.__new__(S, ...) -> a new object with type S, a subtype of T | | nneeww__iinnssttaannccee = - | Signature : () -> example.Example2 + | Signature : () -> example.ExamplePythonTypes | | Return an instance __name__(example) = example -__name__(example.Example2) = Example2 -__module__(example.Example2) = example -__name__(example.Example2.get_set) = get_set -__module__(example.Example2.get_set) = example -Destructing Example2 +__name__(example.ExamplePythonTypes) = ExamplePythonTypes +__module__(example.ExamplePythonTypes) = example +__name__(example.ExamplePythonTypes.get_set) = get_set +__module__(example.ExamplePythonTypes.get_set) = example +Destructing ExamplePythonTypes diff --git a/example/example6.cpp b/example/example-sequences-and-iterators.cpp similarity index 97% rename from example/example6.cpp rename to example/example-sequences-and-iterators.cpp index e0bfb9e70..423364984 100644 --- a/example/example6.cpp +++ b/example/example-sequences-and-iterators.cpp @@ -1,5 +1,5 @@ /* - example/example6.cpp -- supporting Pythons' sequence protocol, iterators, + example/example-sequences-and-iterators.cpp -- supporting Pythons' sequence protocol, iterators, etc. Copyright (c) 2016 Wenzel Jakob @@ -109,7 +109,7 @@ private: float *m_data; }; -void init_ex6(py::module &m) { +void init_ex_sequences_and_iterators(py::module &m) { py::class_ seq(m, "Sequence"); seq.def(py::init()) diff --git a/example/example6.py b/example/example-sequences-and-iterators.py similarity index 100% rename from example/example6.py rename to example/example-sequences-and-iterators.py diff --git a/example/example6.ref b/example/example-sequences-and-iterators.ref similarity index 100% rename from example/example6.ref rename to example/example-sequences-and-iterators.ref diff --git a/example/example8.cpp b/example/example-smart-ptr.cpp similarity index 97% rename from example/example8.cpp rename to example/example-smart-ptr.cpp index dbdd4218d..7ae1db8d5 100644 --- a/example/example8.cpp +++ b/example/example-smart-ptr.cpp @@ -1,5 +1,5 @@ /* - example/example8.cpp -- binding classes with custom reference counting, + example/example-smart-ptr.cpp -- binding classes with custom reference counting, implicit conversions between types Copyright (c) 2016 Wenzel Jakob @@ -105,7 +105,7 @@ void print_myobject3_2(std::shared_ptr obj) { std::cout << obj->toStr void print_myobject3_3(const std::shared_ptr &obj) { std::cout << obj->toString() << std::endl; } void print_myobject3_4(const std::shared_ptr *obj) { std::cout << (*obj)->toString() << std::endl; } -void init_ex8(py::module &m) { +void init_ex_smart_ptr(py::module &m) { py::class_> obj(m, "Object"); obj.def("getRefCount", &Object::getRefCount); diff --git a/example/example8.py b/example/example-smart-ptr.py similarity index 100% rename from example/example8.py rename to example/example-smart-ptr.py diff --git a/example/example8.ref b/example/example-smart-ptr.ref similarity index 100% rename from example/example8.ref rename to example/example-smart-ptr.ref diff --git a/example/example17.cpp b/example/example-stl-binder-vector.cpp similarity index 84% rename from example/example17.cpp rename to example/example-stl-binder-vector.cpp index 8fd4ad642..fa687a2d6 100644 --- a/example/example17.cpp +++ b/example/example-stl-binder-vector.cpp @@ -1,5 +1,5 @@ /* - example/example17.cpp -- Usage of stl_binders functions + example/example-stl-binder-vector.cpp -- Usage of stl_binders functions Copyright (c) 2016 Sergey Lyskov @@ -24,7 +24,7 @@ std::ostream & operator<<(std::ostream &s, El const&v) { return s; } -void init_ex17(py::module &m) { +void init_ex_stl_binder_vector(py::module &m) { pybind11::class_(m, "El") .def(pybind11::init()); diff --git a/example/example17.py b/example/example-stl-binder-vector.py similarity index 100% rename from example/example17.py rename to example/example-stl-binder-vector.py diff --git a/example/example17.ref b/example/example-stl-binder-vector.ref similarity index 100% rename from example/example17.ref rename to example/example-stl-binder-vector.ref diff --git a/example/example12.cpp b/example/example-virtual-functions.cpp similarity index 56% rename from example/example12.cpp rename to example/example-virtual-functions.cpp index e5555f53a..dc39f2640 100644 --- a/example/example12.cpp +++ b/example/example-virtual-functions.cpp @@ -1,5 +1,5 @@ /* - example/example12.cpp -- overriding virtual functions from Python + example/example-virtual-functions.cpp -- overriding virtual functions from Python Copyright (c) 2016 Wenzel Jakob @@ -11,18 +11,18 @@ #include /* This is an example class that we'll want to be able to extend from Python */ -class Example12 { +class ExampleVirt { public: - Example12(int state) : state(state) { - cout << "Constructing Example12.." << endl; + ExampleVirt(int state) : state(state) { + cout << "Constructing ExampleVirt.." << endl; } - ~Example12() { - cout << "Destructing Example12.." << endl; + ~ExampleVirt() { + cout << "Destructing ExampleVirt.." << endl; } virtual int run(int value) { - std::cout << "Original implementation of Example12::run(state=" << state + std::cout << "Original implementation of ExampleVirt::run(state=" << state << ", value=" << value << ")" << std::endl; return state + value; } @@ -34,24 +34,24 @@ private: }; /* This is a wrapper class that must be generated */ -class PyExample12 : public Example12 { +class PyExampleVirt : public ExampleVirt { public: - using Example12::Example12; /* Inherit constructors */ + using ExampleVirt::ExampleVirt; /* Inherit constructors */ virtual int run(int value) { /* Generate wrapping code that enables native function overloading */ PYBIND11_OVERLOAD( - int, /* Return type */ - Example12, /* Parent class */ - run, /* Name of function */ - value /* Argument(s) */ + int, /* Return type */ + ExampleVirt, /* Parent class */ + run, /* Name of function */ + value /* Argument(s) */ ); } virtual bool run_bool() { PYBIND11_OVERLOAD_PURE( bool, /* Return type */ - Example12, /* Parent class */ + ExampleVirt, /* Parent class */ run_bool, /* Name of function */ /* This function has no arguments. The trailing comma in the previous line is needed for some compilers */ @@ -61,7 +61,7 @@ public: virtual void pure_virtual() { PYBIND11_OVERLOAD_PURE( void, /* Return type */ - Example12, /* Parent class */ + ExampleVirt, /* Parent class */ pure_virtual, /* Name of function */ /* This function has no arguments. The trailing comma in the previous line is needed for some compilers */ @@ -69,30 +69,30 @@ public: } }; -int runExample12(Example12 *ex, int value) { +int runExampleVirt(ExampleVirt *ex, int value) { return ex->run(value); } -bool runExample12Bool(Example12* ex) { +bool runExampleVirtBool(ExampleVirt* ex) { return ex->run_bool(); } -void runExample12Virtual(Example12 *ex) { +void runExampleVirtVirtual(ExampleVirt *ex) { ex->pure_virtual(); } -void init_ex12(py::module &m) { - /* Important: indicate the trampoline class PyExample12 using the third +void init_ex_virtual_functions(py::module &m) { + /* Important: indicate the trampoline class PyExampleVirt using the third argument to py::class_. The second argument with the unique pointer is simply the default holder type used by pybind11. */ - py::class_, PyExample12>(m, "Example12") + py::class_, PyExampleVirt>(m, "ExampleVirt") .def(py::init()) /* Reference original class in function definitions */ - .def("run", &Example12::run) - .def("run_bool", &Example12::run_bool) - .def("pure_virtual", &Example12::pure_virtual); + .def("run", &ExampleVirt::run) + .def("run_bool", &ExampleVirt::run_bool) + .def("pure_virtual", &ExampleVirt::pure_virtual); - m.def("runExample12", &runExample12); - m.def("runExample12Bool", &runExample12Bool); - m.def("runExample12Virtual", &runExample12Virtual); + m.def("runExampleVirt", &runExampleVirt); + m.def("runExampleVirtBool", &runExampleVirtBool); + m.def("runExampleVirtVirtual", &runExampleVirtVirtual); } diff --git a/example/example-virtual-functions.py b/example/example-virtual-functions.py new file mode 100644 index 000000000..958001965 --- /dev/null +++ b/example/example-virtual-functions.py @@ -0,0 +1,36 @@ +#!/usr/bin/env python +from __future__ import print_function +import sys +sys.path.append('.') + +from example import ExampleVirt, runExampleVirt, runExampleVirtVirtual, runExampleVirtBool + + +class ExtendedExampleVirt(ExampleVirt): + def __init__(self, state): + super(ExtendedExampleVirt, self).__init__(state + 1) + self.data = "Hello world" + + def run(self, value): + print('ExtendedExampleVirt::run(%i), calling parent..' % value) + return super(ExtendedExampleVirt, self).run(value + 1) + + def run_bool(self): + print('ExtendedExampleVirt::run_bool()') + return False + + def pure_virtual(self): + print('ExtendedExampleVirt::pure_virtual(): %s' % self.data) + + +ex12 = ExampleVirt(10) +print(runExampleVirt(ex12, 20)) +try: + runExampleVirtVirtual(ex12) +except Exception as e: + print("Caught expected exception: " + str(e)) + +ex12p = ExtendedExampleVirt(10) +print(runExampleVirt(ex12p, 20)) +print(runExampleVirtBool(ex12p)) +runExampleVirtVirtual(ex12p) diff --git a/example/example-virtual-functions.ref b/example/example-virtual-functions.ref new file mode 100644 index 000000000..e2071ad8a --- /dev/null +++ b/example/example-virtual-functions.ref @@ -0,0 +1,13 @@ +Constructing ExampleVirt.. +Original implementation of ExampleVirt::run(state=10, value=20) +30 +Caught expected exception: Tried to call pure virtual function "ExampleVirt::pure_virtual" +Constructing ExampleVirt.. +ExtendedExampleVirt::run(20), calling parent.. +Original implementation of ExampleVirt::run(state=11, value=21) +32 +ExtendedExampleVirt::run_bool() +False +ExtendedExampleVirt::pure_virtual(): Hello world +Destructing ExampleVirt.. +Destructing ExampleVirt.. diff --git a/example/example.cpp b/example/example.cpp index ad37273da..e62fde72d 100644 --- a/example/example.cpp +++ b/example/example.cpp @@ -9,25 +9,25 @@ #include "example.h" -void init_ex1(py::module &); -void init_ex2(py::module &); -void init_ex3(py::module &); -void init_ex4(py::module &); -void init_ex5(py::module &); -void init_ex6(py::module &); -void init_ex7(py::module &); -void init_ex8(py::module &); -void init_ex9(py::module &); -void init_ex10(py::module &); -void init_ex11(py::module &); -void init_ex12(py::module &); -void init_ex13(py::module &); -void init_ex14(py::module &); -void init_ex15(py::module &); -void init_ex16(py::module &); -void init_ex17(py::module &); -void init_ex18(py::module &); -void init_ex19(py::module &); +void init_ex_methods_and_attributes(py::module &); +void init_ex_python_types(py::module &); +void init_ex_operator_overloading(py::module &); +void init_ex_constants_and_functions(py::module &); +void init_ex_callbacks(py::module &); +void init_ex_sequences_and_iterators(py::module &); +void init_ex_buffers(py::module &); +void init_ex_smart_ptr(py::module &); +void init_ex_modules(py::module &); +void init_ex_numpy_vectorize(py::module &); +void init_ex_arg_keywords_and_defaults(py::module &); +void init_ex_virtual_functions(py::module &); +void init_ex_keep_alive(py::module &); +void init_ex_opaque_types(py::module &); +void init_ex_pickling(py::module &); +void init_ex_inheritance(py::module &); +void init_ex_stl_binder_vector(py::module &); +void init_ex_eval(py::module &); +void init_ex_custom_exceptions(py::module &); void init_issues(py::module &); #if defined(PYBIND11_TEST_EIGEN) @@ -37,25 +37,25 @@ void init_issues(py::module &); PYBIND11_PLUGIN(example) { py::module m("example", "pybind example plugin"); - init_ex1(m); - init_ex2(m); - init_ex3(m); - init_ex4(m); - init_ex5(m); - init_ex6(m); - init_ex7(m); - init_ex8(m); - init_ex9(m); - init_ex10(m); - init_ex11(m); - init_ex12(m); - init_ex13(m); - init_ex14(m); - init_ex15(m); - init_ex16(m); - init_ex17(m); - init_ex18(m); - init_ex19(m); + init_ex_methods_and_attributes(m); + init_ex_python_types(m); + init_ex_operator_overloading(m); + init_ex_constants_and_functions(m); + init_ex_callbacks(m); + init_ex_sequences_and_iterators(m); + init_ex_buffers(m); + init_ex_smart_ptr(m); + init_ex_modules(m); + init_ex_numpy_vectorize(m); + init_ex_arg_keywords_and_defaults(m); + init_ex_virtual_functions(m); + init_ex_keep_alive(m); + init_ex_opaque_types(m); + init_ex_pickling(m); + init_ex_inheritance(m); + init_ex_stl_binder_vector(m); + init_ex_eval(m); + init_ex_custom_exceptions(m); init_issues(m); #if defined(PYBIND11_TEST_EIGEN) diff --git a/example/example1.cpp b/example/example1.cpp deleted file mode 100644 index dd651fbaf..000000000 --- a/example/example1.cpp +++ /dev/null @@ -1,92 +0,0 @@ -/* - example/example1.cpp -- constructors, deconstructors, attribute access, - __str__, argument and return value conventions - - Copyright (c) 2016 Wenzel Jakob - - All rights reserved. Use of this source code is governed by a - BSD-style license that can be found in the LICENSE file. -*/ - -#include "example.h" - -class Example1 { -public: - Example1() { - cout << "Called Example1 default constructor.." << endl; - } - Example1(int value) : value(value) { - cout << "Called Example1 constructor with value " << value << ".." << endl; - } - Example1(const Example1 &e) : value(e.value) { - cout << "Called Example1 copy constructor with value " << value << ".." << endl; - } - Example1(Example1 &&e) : value(e.value) { - cout << "Called Example1 move constructor with value " << value << ".." << endl; - e.value = 0; - } - ~Example1() { - cout << "Called Example1 destructor (" << value << ")" << endl; - } - std::string toString() { - return "Example1[value=" + std::to_string(value) + "]"; - } - - void operator=(const Example1 &e) { cout << "Assignment operator" << endl; value = e.value; } - void operator=(Example1 &&e) { cout << "Move assignment operator" << endl; value = e.value; e.value = 0;} - - void add1(Example1 other) { value += other.value; } // passing by value - void add2(Example1 &other) { value += other.value; } // passing by reference - void add3(const Example1 &other) { value += other.value; } // passing by const reference - void add4(Example1 *other) { value += other->value; } // passing by pointer - void add5(const Example1 *other) { value += other->value; } // passing by const pointer - - void add6(int other) { value += other; } // passing by value - void add7(int &other) { value += other; } // passing by reference - void add8(const int &other) { value += other; } // passing by const reference - void add9(int *other) { value += *other; } // passing by pointer - void add10(const int *other) { value += *other; } // passing by const pointer - - Example1 self1() { return *this; } // return by value - Example1 &self2() { return *this; } // return by reference - const Example1 &self3() { return *this; } // return by const reference - Example1 *self4() { return this; } // return by pointer - const Example1 *self5() { return this; } // return by const pointer - - int internal1() { return value; } // return by value - int &internal2() { return value; } // return by reference - const int &internal3() { return value; } // return by const reference - int *internal4() { return &value; } // return by pointer - const int *internal5() { return &value; } // return by const pointer - - int value = 0; -}; - -void init_ex1(py::module &m) { - py::class_(m, "Example1") - .def(py::init<>()) - .def(py::init()) - .def(py::init()) - .def("add1", &Example1::add1) - .def("add2", &Example1::add2) - .def("add3", &Example1::add3) - .def("add4", &Example1::add4) - .def("add5", &Example1::add5) - .def("add6", &Example1::add6) - .def("add7", &Example1::add7) - .def("add8", &Example1::add8) - .def("add9", &Example1::add9) - .def("add10", &Example1::add10) - .def("self1", &Example1::self1) - .def("self2", &Example1::self2) - .def("self3", &Example1::self3) - .def("self4", &Example1::self4) - .def("self5", &Example1::self5) - .def("internal1", &Example1::internal1) - .def("internal2", &Example1::internal2) - .def("internal3", &Example1::internal3) - .def("internal4", &Example1::internal4) - .def("internal5", &Example1::internal5) - .def("__str__", &Example1::toString) - .def_readwrite("value", &Example1::value); -} diff --git a/example/example1.ref b/example/example1.ref deleted file mode 100644 index 2c242f9c4..000000000 --- a/example/example1.ref +++ /dev/null @@ -1,26 +0,0 @@ -Called Example1 default constructor.. -Called Example1 constructor with value 32.. -Called Example1 copy constructor with value 32.. -Called Example1 copy constructor with value 32.. -Called Example1 destructor (32) -Called Example1 destructor (32) -Instance 1: Example1[value=320] -Instance 2: Example1[value=32] -Called Example1 copy constructor with value 320.. -Called Example1 move constructor with value 320.. -Called Example1 destructor (0) -Example1[value=320] -Called Example1 destructor (320) -Example1[value=320] -Example1[value=320] -Example1[value=320] -Example1[value=320] -320 -320 -320 -320 -320 -Instance 1, direct access = 320 -Instance 1: Example1[value=100] -Called Example1 destructor (32) -Called Example1 destructor (100) diff --git a/example/example12.py b/example/example12.py deleted file mode 100644 index eb175239f..000000000 --- a/example/example12.py +++ /dev/null @@ -1,36 +0,0 @@ -#!/usr/bin/env python -from __future__ import print_function -import sys -sys.path.append('.') - -from example import Example12, runExample12, runExample12Virtual, runExample12Bool - - -class ExtendedExample12(Example12): - def __init__(self, state): - super(ExtendedExample12, self).__init__(state + 1) - self.data = "Hello world" - - def run(self, value): - print('ExtendedExample12::run(%i), calling parent..' % value) - return super(ExtendedExample12, self).run(value + 1) - - def run_bool(self): - print('ExtendedExample12::run_bool()') - return False - - def pure_virtual(self): - print('ExtendedExample12::pure_virtual(): %s' % self.data) - - -ex12 = Example12(10) -print(runExample12(ex12, 20)) -try: - runExample12Virtual(ex12) -except Exception as e: - print("Caught expected exception: " + str(e)) - -ex12p = ExtendedExample12(10) -print(runExample12(ex12p, 20)) -print(runExample12Bool(ex12p)) -runExample12Virtual(ex12p) diff --git a/example/example12.ref b/example/example12.ref deleted file mode 100644 index a25023fae..000000000 --- a/example/example12.ref +++ /dev/null @@ -1,13 +0,0 @@ -Constructing Example12.. -Original implementation of Example12::run(state=10, value=20) -30 -Caught expected exception: Tried to call pure virtual function "Example12::pure_virtual" -Constructing Example12.. -ExtendedExample12::run(20), calling parent.. -Original implementation of Example12::run(state=11, value=21) -32 -ExtendedExample12::run_bool() -False -ExtendedExample12::pure_virtual(): Hello world -Destructing Example12.. -Destructing Example12.. diff --git a/example/example16.cpp b/example/example16.cpp deleted file mode 100644 index 7b676a9dc..000000000 --- a/example/example16.cpp +++ /dev/null @@ -1,24 +0,0 @@ -/* - example/example16.cpp -- automatic upcasting for polymorphic types - - Copyright (c) 2016 Wenzel Jakob - - All rights reserved. Use of this source code is governed by a - BSD-style license that can be found in the LICENSE file. -*/ - -#include "example.h" - -struct BaseClass { virtual ~BaseClass() {} }; -struct DerivedClass1 : BaseClass { }; -struct DerivedClass2 : BaseClass { }; - -void init_ex16(py::module &m) { - py::class_(m, "BaseClass").def(py::init<>()); - py::class_(m, "DerivedClass1").def(py::init<>()); - py::class_(m, "DerivedClass2").def(py::init<>()); - - m.def("return_class_1", []() -> BaseClass* { return new DerivedClass1(); }); - m.def("return_class_2", []() -> BaseClass* { return new DerivedClass2(); }); - m.def("return_none", []() -> BaseClass* { return nullptr; }); -} diff --git a/example/example18.py b/example/example18.py deleted file mode 100644 index 314e64de3..000000000 --- a/example/example18.py +++ /dev/null @@ -1,5 +0,0 @@ -from example import example18 - -example18() - - diff --git a/example/example4.py b/example/example4.py deleted file mode 100755 index 37d952f2b..000000000 --- a/example/example4.py +++ /dev/null @@ -1,58 +0,0 @@ -#!/usr/bin/env python -from __future__ import print_function -import sys -sys.path.append('.') - -from example import test_function -from example import some_constant -from example import EMyEnumeration -from example import EFirstEntry -from example import Example4 -from example import return_bytes -from example import print_bytes - -print(EMyEnumeration) -print(EMyEnumeration.EFirstEntry) -print(EMyEnumeration.ESecondEntry) -print(EFirstEntry) - -print(test_function()) -print(test_function(7)) -print(test_function(EMyEnumeration.EFirstEntry)) -print(test_function(EMyEnumeration.ESecondEntry)) -print("enum->integer = %i" % int(EMyEnumeration.ESecondEntry)) -print("integer->enum = %s" % str(EMyEnumeration(2))) - -print("A constant = " + str(some_constant)) - -print(Example4.EMode) -print(Example4.EMode.EFirstMode) -print(Example4.EFirstMode) -Example4.test_function(Example4.EFirstMode) - -print("Equality test 1: " + str( - Example4.test_function(Example4.EFirstMode) == - Example4.test_function(Example4.EFirstMode))) - -print("Inequality test 1: " + str( - Example4.test_function(Example4.EFirstMode) != - Example4.test_function(Example4.EFirstMode))) - -print("Equality test 2: " + str( - Example4.test_function(Example4.EFirstMode) == - Example4.test_function(Example4.ESecondMode))) - -print("Inequality test 2: " + str( - Example4.test_function(Example4.EFirstMode) != - Example4.test_function(Example4.ESecondMode))) - -x = { - Example4.test_function(Example4.EFirstMode): 1, - Example4.test_function(Example4.ESecondMode): 2 -} - -x[Example4.test_function(Example4.EFirstMode)] = 3 -x[Example4.test_function(Example4.ESecondMode)] = 4 -print("Hashing test = " + str(x)) - -print_bytes(return_bytes()) diff --git a/example/run_test.py b/example/run_test.py index 90fec0675..e3170281d 100755 --- a/example/run_test.py +++ b/example/run_test.py @@ -24,7 +24,7 @@ def sanitize(lines): line = line.replace('__builtin__', 'builtins') line = line.replace('example.', '') line = line.replace('unicode', 'str') - line = line.replace('Example4.EMode', 'EMode') + line = line.replace('ExampleWithEnum.EMode', 'EMode') line = line.replace('example.EMode', 'EMode') line = line.replace('method of builtins.PyCapsule instance', '') line = line.strip()