pybind11: fix and generalize example

This commit is contained in:
Ciro Santilli 六四事件 法轮功
2020-02-21 00:00:02 +00:00
parent decf7f936e
commit 04a8521905
5 changed files with 28 additions and 26 deletions

3
.gitignore vendored
View File

@ -25,8 +25,11 @@ __pycache__
# Accidents.
/core
/m5out
# In-tree userland builds.
*.o
*.out
*.so
# Kernel modules.
*.ko

View File

@ -1,24 +0,0 @@
#include <string>
#include <pybind11/pybind11.h>
struct Pet {
Pet(const std::string &name) : name(name) { }
void setName(const std::string &name_) { name = name_; }
const std::string &getName() const { return name; }
std::string name;
};
namespace py = pybind11;
PYBIND11_PLUGIN(example) {
py::module m("example", "pybind11 example plugin");
py::class_<Pet>(m, "Pet")
.def(py::init<const std::string &>())
.def("setName", &Pet::setName)
.def("getName", &Pet::getName);
return m.ptr();
}

View File

@ -0,0 +1,22 @@
#include <string>
#include <pybind11/pybind11.h>
struct ClassTest {
ClassTest(const std::string &name) : name(name) { }
void setName(const std::string &name_) { name = name_; }
const std::string &getName() const { return name; }
std::string name;
};
namespace py = pybind11;
PYBIND11_PLUGIN(class_test) {
py::module m("my_module", "pybind11 example plugin");
py::class_<ClassTest>(m, "ClassTest")
.def(py::init<const std::string &>())
.def("setName", &ClassTest::setName)
.def("getName", &ClassTest::getName)
.def_readwrite("name", &ClassTest::name);
return m.ptr();
}

View File

@ -6,3 +6,4 @@ my_class_test = class_test.ClassTest("abc");
print(my_class_test.getName())
my_class_test.setName("012")
print(my_class_test.getName())
assert(my_class_test.getName() == my_class_test.name)

View File

@ -1,4 +1,4 @@
#!/usr/bin/env bash
set -eu
g++ -O3 -Wall -shared -std=c++11 -fPIC class_test.cpp -o class_test`python3-config --extension-suffix` -I /usr/include/python3.6m
set -eux
g++ `python3-config --cflags` -shared -std=c++11 -fPIC class_test.cpp -o class_test`python3-config --extension-suffix` `python3-config --libs`
./class_test_main.py