Skip to content

Instantly share code, notes, and snippets.

@blapid
Last active March 10, 2018 10:30
Show Gist options
  • Save blapid/26d82fad2ae59744cbebe6bfa0235270 to your computer and use it in GitHub Desktop.
Save blapid/26d82fad2ae59744cbebe6bfa0235270 to your computer and use it in GitHub Desktop.
pybind11 issue examples
#include <stdio.h>
#include <list>
#include <memory>
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
struct B;
struct A {
A() {};
~A() {
printf("~A()\n");
if (!b_list.empty()) {
printf("b_list not empty!\n");
}
};
void register_b(B *b) {
b_list.push_back(b);
};
void unregister_b(B *b) {
auto removed = std::remove(b_list.begin(), b_list.end(), b);
b_list.erase(removed, b_list.end());
};
std::list<B *> b_list;
};
struct B {
B(A& a) : m_a(a) {
m_a.register_b(this);
};
~B() {
printf("~B()\n");
m_a.unregister_b(this);
};
A& m_a;
};
namespace py = pybind11;
PYBIND11_MODULE(example, m) {
py::class_<B>(m, "B");
py::class_<A>(m, "A")
.def(py::init<>())
.def("get_b_list", [](A& _this) -> std::vector<B> {
std::vector<B> b_vec;
b_vec.push_back({_this});
b_vec.push_back({_this});
return b_vec;
#if 1 // Switch between implementation described in the issue
});
#else
}, py::return_value_policy::move, py::keep_alive<0, 1>());
#endif
}
import example
a = example.A()
b1 = a.get_b_list()
print b1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment