Skip to content

Commit 6cfebdc

Browse files
committed
working boost::python example
1 parent 98ea003 commit 6cfebdc

File tree

3 files changed

+70
-0
lines changed

3 files changed

+70
-0
lines changed

tests/CMakeLists.txt

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -257,3 +257,9 @@ add_subdirectory(test_embed)
257257

258258
# Test CMake build using functions and targets from subdirectory or installed location
259259
add_subdirectory(test_cmake_build)
260+
261+
find_package(Boost REQUIRED COMPONENTS python${PYTHON_VERSION_MAJOR})
262+
add_library(test_move_arg_bp SHARED test_move_arg_bp.cpp)
263+
target_include_directories(test_move_arg_bp PRIVATE ${PYTHON_INCLUDE_DIRS} ${Boost_INCLUDE_DIRS})
264+
target_link_libraries(test_move_arg_bp ${Boost_LIBRARIES} ${PYTHON_LIBRARIES})
265+
set_target_properties(test_move_arg_bp PROPERTIES LIBRARY_OUTPUT_DIRECTORY ${testdir} PREFIX "")

tests/test_move_arg_bp.cpp

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
#include "test_move_arg.h"
2+
#include <boost/python.hpp>
3+
#include <sstream>
4+
5+
namespace py = boost::python;
6+
7+
std::string item_repr(const Item& item) {
8+
std::stringstream ss;
9+
ss << "py " << item;
10+
return ss.str();
11+
}
12+
13+
void item_access(const Item& item) {
14+
std::cout << "access " << item << "\n";
15+
}
16+
17+
void item_access_ptr(const std::auto_ptr<Item>& item) {
18+
std::cout << "access ptr " << item.get() << " ";
19+
if (item.get()) std::cout << *item;
20+
std::cout << "\n";
21+
}
22+
23+
void item_consume(std::auto_ptr<Item>& item) {
24+
std::cout << "consume " << *item << "\n ";
25+
Item sink(std::move(*item.release()));
26+
std::cout << " old: " << item.get() << "\n new: " << sink << "\n";
27+
}
28+
29+
BOOST_PYTHON_MODULE(test_move_arg_bp) {
30+
py::class_<Item, std::auto_ptr<Item>, boost::noncopyable>("Item", py::init<int>())
31+
.def("__repr__", &item_repr);
32+
33+
py::def("access", item_access);
34+
py::def("access_ptr", item_access_ptr);
35+
36+
py::def("consume", item_consume);
37+
}

tests/test_move_arg_bp.py

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
import pytest
2+
from test_move_arg_bp import Item, access, access_ptr, consume
3+
4+
5+
def test():
6+
item = Item(42)
7+
other = item
8+
print(item)
9+
access(item)
10+
consume(item)
11+
print("back in python")
12+
13+
try:
14+
access_ptr(item)
15+
access(item)
16+
except Exception as e:
17+
print(e)
18+
19+
del item
20+
21+
try:
22+
print(other)
23+
except Exception as e:
24+
print(e)
25+
26+
if __name__ == "__main__":
27+
test()

0 commit comments

Comments
 (0)