Skip to content

Instantly share code, notes, and snippets.

@aldanor
Created September 3, 2016 15:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aldanor/d16135af20205c07c324e5e27f685203 to your computer and use it in GitHub Desktop.
Save aldanor/d16135af20205c07c324e5e27f685203 to your computer and use it in GitHub Desktop.
#include <iostream>
#include <pybind11/pybind11.h>
namespace py = pybind11;
struct Foo { int v; Foo(int v) : v(v) {} };
PYBIND11_PLUGIN(test_untracked) {
py::module m("test_untracked");
py::class_<Foo>(m, "Foo")
.def(py::init<int>());
m.def("make_tracked", [](int i) -> Foo { return {i}; });
m.def("make_untracked", [](int i) -> Foo { return {i}; },
py::return_value_policy::copy_untracked);
m.def("take_by_value", [](Foo f) { return f.v; });
m.def("take_by_ref", [](Foo& f) { return f.v; });
m.def("take_by_cref", [](const Foo& f) { return f.v; });
return m.ptr();
}
from test_untracked import make_tracked, make_untracked, take_by_value, take_by_ref, take_by_cref
t = make_tracked(42)
assert take_by_value(t) == 42
assert take_by_ref(t) == 42
assert take_by_cref(t) == 42
u = make_untracked(2016)
assert take_by_value(u) == 2016
try:
take_by_ref(u)
raise Exception
except TypeError:
pass
try:
take_by_cref(u)
raise Exception
except TypeError:
pass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment