Rename examples files, as per #288

This renames example files from `exampleN` to `example-description`.

Specifically, the following renaming is applied:

example1 -> example-methods-and-attributes
example2 -> example-python-types
example3 -> example-operator-overloading
example4 -> example-constants-and-functions
example5 -> example-callbacks (*)
example6 -> example-sequence-and-iterators
example7 -> example-buffers
example8 -> example-custom-ref-counting
example9 -> example-modules
example10 -> example-numpy-vectorize
example11 -> example-arg-keywords-and-defaults
example12 -> example-virtual-functions
example13 -> example-keep-alive
example14 -> example-opaque-types
example15 -> example-pickling
example16 -> example-inheritance
example17 -> example-stl-binders
example18 -> example-eval
example19 -> example-custom-exceptions

* the inheritance parts of example5 are moved into example-inheritance
(previously example16), and the remainder is left as example-callbacks.

This commit also renames the internal variables ("Example1",
"Example2", "Example4", etc.) into non-numeric names ("ExampleMandA",
"ExamplePythonTypes", "ExampleWithEnum", etc.) to correspond to the
file renaming.

The order of tests is preserved, but this can easily be changed if
there is some more natural ordering by updating the list in
examples/CMakeLists.txt.
This commit is contained in:
Jason Rhinelander 2016-07-18 16:43:18 -04:00
parent fb6aed2157
commit b3f3d79f4c
68 changed files with 517 additions and 517 deletions

View File

@ -7,25 +7,25 @@ if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES)
endif() endif()
set(PYBIND11_EXAMPLES set(PYBIND11_EXAMPLES
example1.cpp example-methods-and-attributes.cpp
example2.cpp example-python-types.cpp
example3.cpp example-operator-overloading.cpp
example4.cpp example-constants-and-functions.cpp
example5.cpp example-callbacks.cpp
example6.cpp example-sequences-and-iterators.cpp
example7.cpp example-buffers.cpp
example8.cpp example-smart-ptr.cpp
example9.cpp example-modules.cpp
example10.cpp example-numpy-vectorize.cpp
example11.cpp example-arg-keywords-and-defaults.cpp
example12.cpp example-virtual-functions.cpp
example13.cpp example-keep-alive.cpp
example14.cpp example-opaque-types.cpp
example15.cpp example-pickling.cpp
example16.cpp example-inheritance.cpp
example17.cpp example-stl-binder-vector.cpp
example18.cpp example-eval.cpp
example19.cpp example-custom-exceptions.cpp
issues.cpp issues.cpp
) )

View File

@ -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 <wenzel.jakob@epfl.ch> Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
@ -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_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_func2", &kw_func, py::arg("x") = 100, py::arg("y") = 200);
m.def("kw_func3", [](const char *) { }, py::arg("data") = std::string("Hello world!")); m.def("kw_func3", [](const char *) { }, py::arg("data") = std::string("Hello world!"));

View File

@ -1,5 +1,5 @@
/* /*
example/example7.cpp -- supporting Pythons' buffer protocol example/example-buffers.cpp -- supporting Pythons' buffer protocol
Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch> Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
@ -73,7 +73,7 @@ private:
float *m_data; float *m_data;
}; };
void init_ex7(py::module &m) { void init_ex_buffers(py::module &m) {
py::class_<Matrix> mtx(m, "Matrix"); py::class_<Matrix> mtx(m, "Matrix");
mtx.def(py::init<size_t, size_t>()) mtx.def(py::init<size_t, size_t>())

View File

@ -1,6 +1,5 @@
/* /*
example/example5.cpp -- inheritance, callbacks, acquiring and releasing the example/example-callbacks.cpp -- callbacks
global interpreter lock
Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch> Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
@ -12,36 +11,6 @@
#include <pybind11/functional.h> #include <pybind11/functional.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();
}
bool test_callback1(py::object func) { bool test_callback1(py::object func) {
func(); func();
return false; return false;
@ -88,24 +57,7 @@ void test_dummy_function(const std::function<int(int)> &f) {
} }
} }
void init_ex5(py::module &m) { void init_ex_callbacks(py::module &m) {
py::class_<Pet> pet_class(m, "Pet");
pet_class
.def(py::init<std::string, std::string>())
.def("name", &Pet::name)
.def("species", &Pet::species);
/* One way of declaring a subclass relationship: reference parent's class_ object */
py::class_<Dog>(m, "Dog", pet_class)
.def(py::init<std::string>());
/* Another way of declaring a subclass relationship: reference parent's C++ type */
py::class_<Rabbit>(m, "Rabbit", py::base<Pet>())
.def(py::init<std::string>());
m.def("pet_print", pet_print);
m.def("dog_bark", dog_bark);
m.def("test_callback1", &test_callback1); m.def("test_callback1", &test_callback1);
m.def("test_callback2", &test_callback2); m.def("test_callback2", &test_callback2);
m.def("test_callback3", &test_callback3); m.def("test_callback3", &test_callback3);

View File

@ -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 <wenzel.jakob@epfl.ch> Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
@ -14,7 +14,7 @@ enum EMyEnumeration {
ESecondEntry ESecondEntry
}; };
class Example4 { class ExampleWithEnum {
public: public:
enum EMode { enum EMode {
EFirstMode = 1, EFirstMode = 1,
@ -22,7 +22,7 @@ public:
}; };
static EMode test_function(EMode mode) { 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; return mode;
} }
}; };
@ -52,7 +52,7 @@ void print_bytes(py::bytes bytes) {
std::cout << "bytes[" << i << "]=" << (int) value[i] << std::endl; 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_function1);
m.def("test_function", &test_function2); m.def("test_function", &test_function2);
m.def("test_function", &test_function3); m.def("test_function", &test_function3);
@ -63,11 +63,11 @@ void init_ex4(py::module &m) {
.value("ESecondEntry", ESecondEntry) .value("ESecondEntry", ESecondEntry)
.export_values(); .export_values();
py::class_<Example4> ex4_class(m, "Example4"); py::class_<ExampleWithEnum> exenum_class(m, "ExampleWithEnum");
ex4_class.def_static("test_function", &Example4::test_function); exenum_class.def_static("test_function", &ExampleWithEnum::test_function);
py::enum_<Example4::EMode>(ex4_class, "EMode") py::enum_<ExampleWithEnum::EMode>(exenum_class, "EMode")
.value("EFirstMode", Example4::EFirstMode) .value("EFirstMode", ExampleWithEnum::EFirstMode)
.value("ESecondMode", Example4::ESecondMode) .value("ESecondMode", ExampleWithEnum::ESecondMode)
.export_values(); .export_values();
m.def("return_bytes", &return_bytes); m.def("return_bytes", &return_bytes);

View File

@ -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())

View File

@ -16,23 +16,23 @@ A constant = 14
<class 'example.EMode'> <class 'example.EMode'>
EMode.EFirstMode EMode.EFirstMode
EMode.EFirstMode EMode.EFirstMode
Example4::test_function(enum=1) ExampleWithEnum::test_function(enum=1)
Example4::test_function(enum=1) ExampleWithEnum::test_function(enum=1)
Example4::test_function(enum=1) ExampleWithEnum::test_function(enum=1)
Equality test 1: True Equality test 1: True
Example4::test_function(enum=1) ExampleWithEnum::test_function(enum=1)
Example4::test_function(enum=1) ExampleWithEnum::test_function(enum=1)
Inequality test 1: False Inequality test 1: False
Example4::test_function(enum=1) ExampleWithEnum::test_function(enum=1)
Example4::test_function(enum=2) ExampleWithEnum::test_function(enum=2)
Equality test 2: False Equality test 2: False
Example4::test_function(enum=1) ExampleWithEnum::test_function(enum=1)
Example4::test_function(enum=2) ExampleWithEnum::test_function(enum=2)
Inequality test 2: True Inequality test 2: True
Example4::test_function(enum=1) ExampleWithEnum::test_function(enum=1)
Example4::test_function(enum=2) ExampleWithEnum::test_function(enum=2)
Example4::test_function(enum=1) ExampleWithEnum::test_function(enum=1)
Example4::test_function(enum=2) ExampleWithEnum::test_function(enum=2)
Hashing test = {EMode.EFirstMode: 3, EMode.ESecondMode: 4} Hashing test = {EMode.EFirstMode: 3, EMode.ESecondMode: 4}
bytes[0]=1 bytes[0]=1
bytes[1]=0 bytes[1]=0

View File

@ -1,5 +1,5 @@
/* /*
example/example19.cpp -- exception translation example/example-custom-exceptions.cpp -- exception translation
Copyright (c) 2016 Pim Schellart <P.Schellart@princeton.edu> Copyright (c) 2016 Pim Schellart <P.Schellart@princeton.edu>
@ -66,7 +66,7 @@ void throws_logic_error() {
throw std::logic_error("this error should fall through to the standard handler"); 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 // make a new custom exception and use it as a translation target
static py::exception<MyException> ex(m, "MyException"); static py::exception<MyException> ex(m, "MyException");
py::register_exception_translator([](std::exception_ptr p) { py::register_exception_translator([](std::exception_ptr p) {

View File

@ -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 Copyright (c) 2016 Klemens D. Morgenstern
@ -11,7 +11,7 @@
#include <pybind11/eval.h> #include <pybind11/eval.h>
#include "example.h" #include "example.h"
void example18() { void example_eval() {
py::module main_module = py::module::import("__main__"); py::module main_module = py::module::import("__main__");
py::object main_namespace = main_module.attr("__dict__"); py::object main_namespace = main_module.attr("__dict__");
@ -59,9 +59,9 @@ void example18() {
main_module.def("call_test2", [&](int value) {val_out = value;}); main_module.def("call_test2", [&](int value) {val_out = value;});
try { try {
result = py::eval_file("example18_call.py", main_namespace); result = py::eval_file("example-eval_call.py", main_namespace);
} catch (...) { } 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()) if (val_out == 42 && result == py::none())
@ -97,6 +97,6 @@ void example18() {
cout << "eval_file failure test failed" << endl; cout << "eval_file failure test failed" << endl;
} }
void init_ex18(py::module & m) { void init_ex_eval(py::module & m) {
m.def("example18", &example18); m.def("example_eval", &example_eval);
} }

5
example/example-eval.py Normal file
View File

@ -0,0 +1,5 @@
from example import example_eval
example_eval()

View File

@ -0,0 +1,72 @@
/*
example/example-inheritance.cpp -- inheritance, automatic upcasting for polymorphic types
Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
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> pet_class(m, "Pet");
pet_class
.def(py::init<std::string, std::string>())
.def("name", &Pet::name)
.def("species", &Pet::species);
/* One way of declaring a subclass relationship: reference parent's class_ object */
py::class_<Dog>(m, "Dog", pet_class)
.def(py::init<std::string>());
/* Another way of declaring a subclass relationship: reference parent's C++ type */
py::class_<Rabbit>(m, "Rabbit", py::base<Pet>())
.def(py::init<std::string>());
m.def("pet_print", pet_print);
m.def("dog_bark", dog_bark);
py::class_<BaseClass>(m, "BaseClass").def(py::init<>());
py::class_<DerivedClass1>(m, "DerivedClass1").def(py::init<>());
py::class_<DerivedClass2>(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; });
}

View File

@ -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) of Boost.Python's with_custodian_and_ward / with_custodian_and_ward_postcall)
Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch> Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
@ -24,7 +24,7 @@ public:
Child *returnChild() { return new Child(); } Child *returnChild() { return new Child(); }
}; };
void init_ex13(py::module &m) { void init_ex_keep_alive(py::module &m) {
py::class_<Parent>(m, "Parent") py::class_<Parent>(m, "Parent")
.def(py::init<>()) .def(py::init<>())
.def("addChild", &Parent::addChild) .def("addChild", &Parent::addChild)

View File

@ -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 <wenzel.jakob@epfl.ch>
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_<ExampleMandA>(m, "ExampleMandA")
.def(py::init<>())
.def(py::init<int>())
.def(py::init<const ExampleMandA&>())
.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);
}

View File

@ -3,10 +3,10 @@ from __future__ import print_function
import sys import sys
sys.path.append('.') sys.path.append('.')
from example import Example1 from example import ExampleMandA
instance1 = Example1() instance1 = ExampleMandA()
instance2 = Example1(32) instance2 = ExampleMandA(32)
instance1.add1(instance2) instance1.add1(instance2)
instance1.add2(instance2) instance1.add2(instance2)
instance1.add3(instance2) instance1.add3(instance2)

View File

@ -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)

View File

@ -1,5 +1,5 @@
/* /*
example/example9.cpp -- nested modules, importing modules, and example/example-modules.cpp -- nested modules, importing modules, and
internal references internal references
Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch> Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
@ -36,7 +36,7 @@ public:
A a2{2}; A a2{2};
}; };
void init_ex9(py::module &m) { void init_ex_modules(py::module &m) {
py::module m_sub = m.def_submodule("submodule"); py::module m_sub = m.def_submodule("submodule");
m_sub.def("submodule_func", &submodule_func); m_sub.def("submodule_func", &submodule_func);

View File

@ -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 arguments
Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch> Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
@ -20,7 +20,7 @@ std::complex<double> my_func3(std::complex<double> c) {
return c * std::complex<double>(2.f); return c * std::complex<double>(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) // Vectorize all arguments of a function (though non-vector arguments are also allowed)
m.def("vectorized_func", py::vectorize(my_func)); m.def("vectorized_func", py::vectorize(my_func));

View File

@ -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 <wenzel.jakob@epfl.ch> Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
@ -21,7 +21,7 @@ public:
/* IMPORTANT: Disable internal pybind11 translation mechanisms for STL data structures */ /* IMPORTANT: Disable internal pybind11 translation mechanisms for STL data structures */
PYBIND11_MAKE_OPAQUE(StringList); PYBIND11_MAKE_OPAQUE(StringList);
void init_ex14(py::module &m) { void init_ex_opaque_types(py::module &m) {
py::class_<StringList>(m, "StringList") py::class_<StringList>(m, "StringList")
.def(py::init<>()) .def(py::init<>())
.def("pop_back", &StringList::pop_back) .def("pop_back", &StringList::pop_back)

View File

@ -8,7 +8,7 @@ from example import ClassWithSTLVecProperty
from example import return_void_ptr, print_void_ptr from example import return_void_ptr, print_void_ptr
from example import return_null_str, print_null_str from example import return_null_str, print_null_str
from example import return_unique_ptr 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(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: try:
print_void_ptr([1, 2, 3]) # This should not work print_void_ptr([1, 2, 3]) # This should not work

View File

@ -6,9 +6,9 @@ Opaque list: [Element 1]
Opaque list: [] Opaque list: []
Opaque list: [Element 1, Element 3] Opaque list: [Element 1, Element 3]
Got void ptr : 0x1234 Got void ptr : 0x1234
Called Example1 default constructor.. Called ExampleMandA default constructor..
Got void ptr : 0x7f9ba0f3c430 Got void ptr : 0x7f9ba0f3c430
Called Example1 destructor (0) Called ExampleMandA destructor (0)
Caught expected exception: Incompatible function arguments. The following argument types are supported: Caught expected exception: Incompatible function arguments. The following argument types are supported:
1. (capsule) -> NoneType 1. (capsule) -> NoneType
Invoked with: [1, 2, 3] Invoked with: [1, 2, 3]

View File

@ -1,5 +1,5 @@
/* /*
example/example3.cpp -- operator overloading example/example-operator-overloading.cpp -- operator overloading
Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch> Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
@ -52,7 +52,7 @@ private:
}; };
void init_ex3(py::module &m) { void init_ex_operator_overloading(py::module &m) {
py::class_<Vector2>(m, "Vector2") py::class_<Vector2>(m, "Vector2")
.def(py::init<float, float>()) .def(py::init<float, float>())
.def(py::self + py::self) .def(py::self + py::self)

View File

@ -1,5 +1,5 @@
/* /*
example/example15.cpp -- pickle support example/example-pickling.cpp -- pickle support
Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch> Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
@ -24,7 +24,7 @@ private:
int m_extra2 = 0; int m_extra2 = 0;
}; };
void init_ex15(py::module &m) { void init_ex_pickling(py::module &m) {
py::class_<Pickleable>(m, "Pickleable") py::class_<Pickleable>(m, "Pickleable")
.def(py::init<std::string>()) .def(py::init<std::string>())
.def("value", &Pickleable::value) .def("value", &Pickleable::value)

View File

@ -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 variables, passing and interacting with Python types
Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch> Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
@ -16,13 +16,13 @@
# include <fcntl.h> # include <fcntl.h>
#endif #endif
class Example2 { class ExamplePythonTypes {
public: public:
static Example2 *new_instance() { static ExamplePythonTypes *new_instance() {
return new Example2(); return new ExamplePythonTypes();
} }
~Example2() { ~ExamplePythonTypes() {
std::cout << "Destructing Example2" << std::endl; std::cout << "Destructing ExamplePythonTypes" << std::endl;
} }
/* Create and return a Python dictionary */ /* Create and return a Python dictionary */
@ -142,31 +142,31 @@ public:
static const int value2; static const int value2;
}; };
int Example2::value = 0; int ExamplePythonTypes::value = 0;
const int Example2::value2 = 5; 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 /* No constructor is explicitly defined below. An exception is raised when
trying to construct it directly from Python */ trying to construct it directly from Python */
py::class_<Example2>(m, "Example2", "Example 2 documentation") py::class_<ExamplePythonTypes>(m, "ExamplePythonTypes", "Example 2 documentation")
.def("get_dict", &Example2::get_dict, "Return a Python dictionary") .def("get_dict", &ExamplePythonTypes::get_dict, "Return a Python dictionary")
.def("get_dict_2", &Example2::get_dict_2, "Return a C++ dictionary") .def("get_dict_2", &ExamplePythonTypes::get_dict_2, "Return a C++ dictionary")
.def("get_list", &Example2::get_list, "Return a Python list") .def("get_list", &ExamplePythonTypes::get_list, "Return a Python list")
.def("get_list_2", &Example2::get_list_2, "Return a C++ list") .def("get_list_2", &ExamplePythonTypes::get_list_2, "Return a C++ list")
.def("get_set", &Example2::get_set, "Return a Python set") .def("get_set", &ExamplePythonTypes::get_set, "Return a Python set")
.def("get_set2", &Example2::get_set_2, "Return a C++ set") .def("get_set2", &ExamplePythonTypes::get_set_2, "Return a C++ set")
.def("get_array", &Example2::get_array, "Return a C++ array") .def("get_array", &ExamplePythonTypes::get_array, "Return a C++ array")
.def("print_dict", &Example2::print_dict, "Print entries of a Python dictionary") .def("print_dict", &ExamplePythonTypes::print_dict, "Print entries of a Python dictionary")
.def("print_dict_2", &Example2::print_dict_2, "Print entries of a C++ dictionary") .def("print_dict_2", &ExamplePythonTypes::print_dict_2, "Print entries of a C++ dictionary")
.def("print_set", &Example2::print_set, "Print entries of a Python set") .def("print_set", &ExamplePythonTypes::print_set, "Print entries of a Python set")
.def("print_set_2", &Example2::print_set_2, "Print entries of a C++ set") .def("print_set_2", &ExamplePythonTypes::print_set_2, "Print entries of a C++ set")
.def("print_list", &Example2::print_list, "Print entries of a Python list") .def("print_list", &ExamplePythonTypes::print_list, "Print entries of a Python list")
.def("print_list_2", &Example2::print_list_2, "Print entries of a C++ list") .def("print_list_2", &ExamplePythonTypes::print_list_2, "Print entries of a C++ list")
.def("print_array", &Example2::print_array, "Print entries of a C++ array") .def("print_array", &ExamplePythonTypes::print_array, "Print entries of a C++ array")
.def("pair_passthrough", &Example2::pair_passthrough, "Return a pair in reversed order") .def("pair_passthrough", &ExamplePythonTypes::pair_passthrough, "Return a pair in reversed order")
.def("tuple_passthrough", &Example2::tuple_passthrough, "Return a triple in reversed order") .def("tuple_passthrough", &ExamplePythonTypes::tuple_passthrough, "Return a triple in reversed order")
.def("throw_exception", &Example2::throw_exception, "Throw an exception") .def("throw_exception", &ExamplePythonTypes::throw_exception, "Throw an exception")
.def_static("new_instance", &Example2::new_instance, "Return an instance") .def_static("new_instance", &ExamplePythonTypes::new_instance, "Return an instance")
.def_readwrite_static("value", &Example2::value, "Static value member") .def_readwrite_static("value", &ExamplePythonTypes::value, "Static value member")
.def_readonly_static("value2", &Example2::value2, "Static value member (readonly)"); .def_readonly_static("value2", &ExamplePythonTypes::value2, "Static value member (readonly)");
} }

View File

@ -4,23 +4,23 @@ import sys, pydoc
sys.path.append('.') sys.path.append('.')
import example import example
from example import Example2 from example import ExamplePythonTypes
Example2.value = 15 ExamplePythonTypes.value = 15
print(Example2.value) print(ExamplePythonTypes.value)
print(Example2.value2) print(ExamplePythonTypes.value2)
try: try:
Example2() ExamplePythonTypes()
except Exception as e: except Exception as e:
print(e) print(e)
try: try:
Example2.value2 = 15 ExamplePythonTypes.value2 = 15
except Exception as e: except Exception as e:
print(e) print(e)
instance = Example2.new_instance() instance = ExamplePythonTypes.new_instance()
dict_result = instance.get_dict() dict_result = instance.get_dict()
dict_result['key2'] = 'value2' dict_result['key2'] = 'value2'
@ -58,10 +58,10 @@ except Exception as e:
print(instance.pair_passthrough((True, "test"))) print(instance.pair_passthrough((True, "test")))
print(instance.tuple_passthrough((True, "test", 5))) 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) = %s" % example.__name__)
print("__name__(example.Example2) = %s" % Example2.__name__) print("__name__(example.ExamplePythonTypes) = %s" % ExamplePythonTypes.__name__)
print("__module__(example.Example2) = %s" % Example2.__module__) print("__module__(example.ExamplePythonTypes) = %s" % ExamplePythonTypes.__module__)
print("__name__(example.Example2.get_set) = %s" % Example2.get_set.__name__) print("__name__(example.ExamplePythonTypes.get_set) = %s" % ExamplePythonTypes.get_set.__name__)
print("__module__(example.Example2.get_set) = %s" % Example2.get_set.__module__) print("__module__(example.ExamplePythonTypes.get_set) = %s" % ExamplePythonTypes.get_set.__module__)

View File

@ -1,6 +1,6 @@
15 15
5 5
example.Example2: No constructor defined! example.ExamplePythonTypes: No constructor defined!
can't set attribute can't set attribute
key: key2, value=value2 key: key2, value=value2
key: key, value=value key: key, value=value
@ -23,9 +23,9 @@ array item 1: array entry 2
This exception was intentionally thrown. This exception was intentionally thrown.
(u'test', True) (u'test', True)
(5L, 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 | Example 2 documentation
| |
| Methods defined here: | Methods defined here:
@ -34,104 +34,104 @@ class EExxaammppllee22(__builtin__.object)
| x.__init__(...) initializes x; see help(type(x)) for signature | x.__init__(...) initializes x; see help(type(x)) for signature
| |
| ggeett__aarrrraayy(...) | ggeett__aarrrraayy(...)
| Signature : (example.Example2) -> list<unicode>[2] | Signature : (example.ExamplePythonTypes) -> list<unicode>[2]
| |
| Return a C++ array | Return a C++ array
| |
| ggeett__ddiicctt(...) | ggeett__ddiicctt(...)
| Signature : (example.Example2) -> dict | Signature : (example.ExamplePythonTypes) -> dict
| |
| Return a Python dictionary | Return a Python dictionary
| |
| ggeett__ddiicctt__22(...) | ggeett__ddiicctt__22(...)
| Signature : (example.Example2) -> dict<unicode, unicode> | Signature : (example.ExamplePythonTypes) -> dict<unicode, unicode>
| |
| Return a C++ dictionary | Return a C++ dictionary
| |
| ggeett__lliisstt(...) | ggeett__lliisstt(...)
| Signature : (example.Example2) -> list | Signature : (example.ExamplePythonTypes) -> list
| |
| Return a Python list | Return a Python list
| |
| ggeett__lliisstt__22(...) | ggeett__lliisstt__22(...)
| Signature : (example.Example2) -> list<unicode> | Signature : (example.ExamplePythonTypes) -> list<unicode>
| |
| Return a C++ list | Return a C++ list
| |
| ggeett__sseett(...) | ggeett__sseett(...)
| Signature : (example.Example2) -> set | Signature : (example.ExamplePythonTypes) -> set
| |
| Return a Python set | Return a Python set
| |
| ggeett__sseett22(...) | ggeett__sseett22(...)
| Signature : (example.Example2) -> set | Signature : (example.ExamplePythonTypes) -> set
| |
| Return a C++ set | Return a C++ set
| |
| ppaaiirr__ppaasssstthhrroouugghh(...) | ppaaiirr__ppaasssstthhrroouugghh(...)
| Signature : (example.Example2, (bool, unicode)) -> (unicode, bool) | Signature : (example.ExamplePythonTypes, (bool, unicode)) -> (unicode, bool)
| |
| Return a pair in reversed order | Return a pair in reversed order
| |
| pprriinntt__aarrrraayy(...) | pprriinntt__aarrrraayy(...)
| Signature : (example.Example2, list<unicode>[2]) -> NoneType | Signature : (example.ExamplePythonTypes, list<unicode>[2]) -> NoneType
| |
| Print entries of a C++ array | Print entries of a C++ array
| |
| pprriinntt__ddiicctt(...) | pprriinntt__ddiicctt(...)
| Signature : (example.Example2, dict) -> NoneType | Signature : (example.ExamplePythonTypes, dict) -> NoneType
| |
| Print entries of a Python dictionary | Print entries of a Python dictionary
| |
| pprriinntt__ddiicctt__22(...) | pprriinntt__ddiicctt__22(...)
| Signature : (example.Example2, dict<unicode, unicode>) -> NoneType | Signature : (example.ExamplePythonTypes, dict<unicode, unicode>) -> NoneType
| |
| Print entries of a C++ dictionary | Print entries of a C++ dictionary
| |
| pprriinntt__lliisstt(...) | pprriinntt__lliisstt(...)
| Signature : (example.Example2, list) -> NoneType | Signature : (example.ExamplePythonTypes, list) -> NoneType
| |
| Print entries of a Python list | Print entries of a Python list
| |
| pprriinntt__lliisstt__22(...) | pprriinntt__lliisstt__22(...)
| Signature : (example.Example2, list<unicode>) -> NoneType | Signature : (example.ExamplePythonTypes, list<unicode>) -> NoneType
| |
| Print entries of a C++ list | Print entries of a C++ list
| |
| pprriinntt__sseett(...) | pprriinntt__sseett(...)
| Signature : (example.Example2, set) -> NoneType | Signature : (example.ExamplePythonTypes, set) -> NoneType
| |
| Print entries of a Python set | Print entries of a Python set
| |
| pprriinntt__sseett__22(...) | pprriinntt__sseett__22(...)
| Signature : (example.Example2, set<unicode>) -> NoneType | Signature : (example.ExamplePythonTypes, set<unicode>) -> NoneType
| |
| Print entries of a C++ set | Print entries of a C++ set
| |
| tthhrrooww__eexxcceeppttiioonn(...) | tthhrrooww__eexxcceeppttiioonn(...)
| Signature : (example.Example2) -> NoneType | Signature : (example.ExamplePythonTypes) -> NoneType
| |
| Throw an exception | Throw an exception
| |
| ttuuppllee__ppaasssstthhrroouugghh(...) | 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 | Return a triple in reversed order
| |
| ---------------------------------------------------------------------- | ----------------------------------------------------------------------
| Data and other attributes defined here: | Data and other attributes defined here:
| |
| ____nneeww____ = <built-in method __new__ of example.Example2__Meta object> | ____nneeww____ = <built-in method __new__ of example.ExamplePythonTypes__Meta object>
| T.__new__(S, ...) -> a new object with type S, a subtype of T | T.__new__(S, ...) -> a new object with type S, a subtype of T
| |
| nneeww__iinnssttaannccee = <built-in method new_instance of PyCapsule object> | nneeww__iinnssttaannccee = <built-in method new_instance of PyCapsule object>
| Signature : () -> example.Example2 | Signature : () -> example.ExamplePythonTypes
| |
| Return an instance | Return an instance
__name__(example) = example __name__(example) = example
__name__(example.Example2) = Example2 __name__(example.ExamplePythonTypes) = ExamplePythonTypes
__module__(example.Example2) = example __module__(example.ExamplePythonTypes) = example
__name__(example.Example2.get_set) = get_set __name__(example.ExamplePythonTypes.get_set) = get_set
__module__(example.Example2.get_set) = example __module__(example.ExamplePythonTypes.get_set) = example
Destructing Example2 Destructing ExamplePythonTypes

View File

@ -1,5 +1,5 @@
/* /*
example/example6.cpp -- supporting Pythons' sequence protocol, iterators, example/example-sequences-and-iterators.cpp -- supporting Pythons' sequence protocol, iterators,
etc. etc.
Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch> Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
@ -109,7 +109,7 @@ private:
float *m_data; float *m_data;
}; };
void init_ex6(py::module &m) { void init_ex_sequences_and_iterators(py::module &m) {
py::class_<Sequence> seq(m, "Sequence"); py::class_<Sequence> seq(m, "Sequence");
seq.def(py::init<size_t>()) seq.def(py::init<size_t>())

View File

@ -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 implicit conversions between types
Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch> Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
@ -105,7 +105,7 @@ void print_myobject3_2(std::shared_ptr<MyObject3> obj) { std::cout << obj->toStr
void print_myobject3_3(const std::shared_ptr<MyObject3> &obj) { std::cout << obj->toString() << std::endl; } void print_myobject3_3(const std::shared_ptr<MyObject3> &obj) { std::cout << obj->toString() << std::endl; }
void print_myobject3_4(const std::shared_ptr<MyObject3> *obj) { std::cout << (*obj)->toString() << std::endl; } void print_myobject3_4(const std::shared_ptr<MyObject3> *obj) { std::cout << (*obj)->toString() << std::endl; }
void init_ex8(py::module &m) { void init_ex_smart_ptr(py::module &m) {
py::class_<Object, ref<Object>> obj(m, "Object"); py::class_<Object, ref<Object>> obj(m, "Object");
obj.def("getRefCount", &Object::getRefCount); obj.def("getRefCount", &Object::getRefCount);

View File

@ -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 Copyright (c) 2016 Sergey Lyskov
@ -24,7 +24,7 @@ std::ostream & operator<<(std::ostream &s, El const&v) {
return s; return s;
} }
void init_ex17(py::module &m) { void init_ex_stl_binder_vector(py::module &m) {
pybind11::class_<El>(m, "El") pybind11::class_<El>(m, "El")
.def(pybind11::init<int>()); .def(pybind11::init<int>());

View File

@ -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 <wenzel.jakob@epfl.ch> Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
@ -11,18 +11,18 @@
#include <pybind11/functional.h> #include <pybind11/functional.h>
/* This is an example class that we'll want to be able to extend from Python */ /* This is an example class that we'll want to be able to extend from Python */
class Example12 { class ExampleVirt {
public: public:
Example12(int state) : state(state) { ExampleVirt(int state) : state(state) {
cout << "Constructing Example12.." << endl; cout << "Constructing ExampleVirt.." << endl;
} }
~Example12() { ~ExampleVirt() {
cout << "Destructing Example12.." << endl; cout << "Destructing ExampleVirt.." << endl;
} }
virtual int run(int value) { 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; << ", value=" << value << ")" << std::endl;
return state + value; return state + value;
} }
@ -34,24 +34,24 @@ private:
}; };
/* This is a wrapper class that must be generated */ /* This is a wrapper class that must be generated */
class PyExample12 : public Example12 { class PyExampleVirt : public ExampleVirt {
public: public:
using Example12::Example12; /* Inherit constructors */ using ExampleVirt::ExampleVirt; /* Inherit constructors */
virtual int run(int value) { virtual int run(int value) {
/* Generate wrapping code that enables native function overloading */ /* Generate wrapping code that enables native function overloading */
PYBIND11_OVERLOAD( PYBIND11_OVERLOAD(
int, /* Return type */ int, /* Return type */
Example12, /* Parent class */ ExampleVirt, /* Parent class */
run, /* Name of function */ run, /* Name of function */
value /* Argument(s) */ value /* Argument(s) */
); );
} }
virtual bool run_bool() { virtual bool run_bool() {
PYBIND11_OVERLOAD_PURE( PYBIND11_OVERLOAD_PURE(
bool, /* Return type */ bool, /* Return type */
Example12, /* Parent class */ ExampleVirt, /* Parent class */
run_bool, /* Name of function */ run_bool, /* Name of function */
/* This function has no arguments. The trailing comma /* This function has no arguments. The trailing comma
in the previous line is needed for some compilers */ in the previous line is needed for some compilers */
@ -61,7 +61,7 @@ public:
virtual void pure_virtual() { virtual void pure_virtual() {
PYBIND11_OVERLOAD_PURE( PYBIND11_OVERLOAD_PURE(
void, /* Return type */ void, /* Return type */
Example12, /* Parent class */ ExampleVirt, /* Parent class */
pure_virtual, /* Name of function */ pure_virtual, /* Name of function */
/* This function has no arguments. The trailing comma /* This function has no arguments. The trailing comma
in the previous line is needed for some compilers */ 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); return ex->run(value);
} }
bool runExample12Bool(Example12* ex) { bool runExampleVirtBool(ExampleVirt* ex) {
return ex->run_bool(); return ex->run_bool();
} }
void runExample12Virtual(Example12 *ex) { void runExampleVirtVirtual(ExampleVirt *ex) {
ex->pure_virtual(); ex->pure_virtual();
} }
void init_ex12(py::module &m) { void init_ex_virtual_functions(py::module &m) {
/* Important: indicate the trampoline class PyExample12 using the third /* Important: indicate the trampoline class PyExampleVirt using the third
argument to py::class_. The second argument with the unique pointer argument to py::class_. The second argument with the unique pointer
is simply the default holder type used by pybind11. */ is simply the default holder type used by pybind11. */
py::class_<Example12, std::unique_ptr<Example12>, PyExample12>(m, "Example12") py::class_<ExampleVirt, std::unique_ptr<ExampleVirt>, PyExampleVirt>(m, "ExampleVirt")
.def(py::init<int>()) .def(py::init<int>())
/* Reference original class in function definitions */ /* Reference original class in function definitions */
.def("run", &Example12::run) .def("run", &ExampleVirt::run)
.def("run_bool", &Example12::run_bool) .def("run_bool", &ExampleVirt::run_bool)
.def("pure_virtual", &Example12::pure_virtual); .def("pure_virtual", &ExampleVirt::pure_virtual);
m.def("runExample12", &runExample12); m.def("runExampleVirt", &runExampleVirt);
m.def("runExample12Bool", &runExample12Bool); m.def("runExampleVirtBool", &runExampleVirtBool);
m.def("runExample12Virtual", &runExample12Virtual); m.def("runExampleVirtVirtual", &runExampleVirtVirtual);
} }

View File

@ -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)

View File

@ -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..

View File

@ -9,25 +9,25 @@
#include "example.h" #include "example.h"
void init_ex1(py::module &); void init_ex_methods_and_attributes(py::module &);
void init_ex2(py::module &); void init_ex_python_types(py::module &);
void init_ex3(py::module &); void init_ex_operator_overloading(py::module &);
void init_ex4(py::module &); void init_ex_constants_and_functions(py::module &);
void init_ex5(py::module &); void init_ex_callbacks(py::module &);
void init_ex6(py::module &); void init_ex_sequences_and_iterators(py::module &);
void init_ex7(py::module &); void init_ex_buffers(py::module &);
void init_ex8(py::module &); void init_ex_smart_ptr(py::module &);
void init_ex9(py::module &); void init_ex_modules(py::module &);
void init_ex10(py::module &); void init_ex_numpy_vectorize(py::module &);
void init_ex11(py::module &); void init_ex_arg_keywords_and_defaults(py::module &);
void init_ex12(py::module &); void init_ex_virtual_functions(py::module &);
void init_ex13(py::module &); void init_ex_keep_alive(py::module &);
void init_ex14(py::module &); void init_ex_opaque_types(py::module &);
void init_ex15(py::module &); void init_ex_pickling(py::module &);
void init_ex16(py::module &); void init_ex_inheritance(py::module &);
void init_ex17(py::module &); void init_ex_stl_binder_vector(py::module &);
void init_ex18(py::module &); void init_ex_eval(py::module &);
void init_ex19(py::module &); void init_ex_custom_exceptions(py::module &);
void init_issues(py::module &); void init_issues(py::module &);
#if defined(PYBIND11_TEST_EIGEN) #if defined(PYBIND11_TEST_EIGEN)
@ -37,25 +37,25 @@ void init_issues(py::module &);
PYBIND11_PLUGIN(example) { PYBIND11_PLUGIN(example) {
py::module m("example", "pybind example plugin"); py::module m("example", "pybind example plugin");
init_ex1(m); init_ex_methods_and_attributes(m);
init_ex2(m); init_ex_python_types(m);
init_ex3(m); init_ex_operator_overloading(m);
init_ex4(m); init_ex_constants_and_functions(m);
init_ex5(m); init_ex_callbacks(m);
init_ex6(m); init_ex_sequences_and_iterators(m);
init_ex7(m); init_ex_buffers(m);
init_ex8(m); init_ex_smart_ptr(m);
init_ex9(m); init_ex_modules(m);
init_ex10(m); init_ex_numpy_vectorize(m);
init_ex11(m); init_ex_arg_keywords_and_defaults(m);
init_ex12(m); init_ex_virtual_functions(m);
init_ex13(m); init_ex_keep_alive(m);
init_ex14(m); init_ex_opaque_types(m);
init_ex15(m); init_ex_pickling(m);
init_ex16(m); init_ex_inheritance(m);
init_ex17(m); init_ex_stl_binder_vector(m);
init_ex18(m); init_ex_eval(m);
init_ex19(m); init_ex_custom_exceptions(m);
init_issues(m); init_issues(m);
#if defined(PYBIND11_TEST_EIGEN) #if defined(PYBIND11_TEST_EIGEN)

View File

@ -1,92 +0,0 @@
/*
example/example1.cpp -- constructors, deconstructors, attribute access,
__str__, argument and return value conventions
Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
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_<Example1>(m, "Example1")
.def(py::init<>())
.def(py::init<int>())
.def(py::init<const Example1&>())
.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);
}

View File

@ -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)

View File

@ -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)

View File

@ -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..

View File

@ -1,24 +0,0 @@
/*
example/example16.cpp -- automatic upcasting for polymorphic types
Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
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_<BaseClass>(m, "BaseClass").def(py::init<>());
py::class_<DerivedClass1>(m, "DerivedClass1").def(py::init<>());
py::class_<DerivedClass2>(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; });
}

View File

@ -1,5 +0,0 @@
from example import example18
example18()

View File

@ -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())

View File

@ -24,7 +24,7 @@ def sanitize(lines):
line = line.replace('__builtin__', 'builtins') line = line.replace('__builtin__', 'builtins')
line = line.replace('example.', '') line = line.replace('example.', '')
line = line.replace('unicode', 'str') 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('example.EMode', 'EMode')
line = line.replace('method of builtins.PyCapsule instance', '') line = line.replace('method of builtins.PyCapsule instance', '')
line = line.strip() line = line.strip()