-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample.cpp
More file actions
40 lines (30 loc) · 1007 Bytes
/
example.cpp
File metadata and controls
40 lines (30 loc) · 1007 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <boost/python.hpp>
#include <memory>
#include <iostream>
using namespace boost::python;
struct Foo {
Foo(int v) : value(v) { std::cout << "Foo(" << value << ") constructed\n"; }
~Foo() { std::cout << "Foo(" << value << ") destroyed\n"; }
void hello() const { std::cout << "Hello from Foo(" << value << ")\n"; }
int value;
};
// --- 1. Owned instance (Python owns) ---
std::shared_ptr<Foo> make_owned(int v) {
return std::make_shared<Foo>(v);
}
// --- 2. Borrowed instance (C++ owns) ---
Foo globalFoo(999);
Foo* get_borrowed() {
return &globalFoo; // still alive for entire program
}
BOOST_PYTHON_MODULE(example)
{
class_<Foo, std::shared_ptr<Foo>>("Foo", init<int>())
.def("hello", &Foo::hello)
.def_readwrite("value", &Foo::value);
// Python owns this one
def("make_owned", &make_owned);
// Python borrows this one (C++ owns it)
def("get_borrowed", &get_borrowed,
return_value_policy<reference_existing_object>());
}