From 6cfebdc7f16589734955214c17900bbd696766bb Mon Sep 17 00:00:00 2001 From: Robert Haschke Date: Mon, 23 Dec 2019 21:59:29 +0100 Subject: [PATCH] working boost::python example --- tests/CMakeLists.txt | 6 ++++++ tests/test_move_arg_bp.cpp | 37 +++++++++++++++++++++++++++++++++++++ tests/test_move_arg_bp.py | 27 +++++++++++++++++++++++++++ 3 files changed, 70 insertions(+) create mode 100644 tests/test_move_arg_bp.cpp create mode 100644 tests/test_move_arg_bp.py diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 8208290c91..e1898a6f6f 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -257,3 +257,9 @@ add_subdirectory(test_embed) # Test CMake build using functions and targets from subdirectory or installed location add_subdirectory(test_cmake_build) + +find_package(Boost REQUIRED COMPONENTS python${PYTHON_VERSION_MAJOR}) +add_library(test_move_arg_bp SHARED test_move_arg_bp.cpp) +target_include_directories(test_move_arg_bp PRIVATE ${PYTHON_INCLUDE_DIRS} ${Boost_INCLUDE_DIRS}) +target_link_libraries(test_move_arg_bp ${Boost_LIBRARIES} ${PYTHON_LIBRARIES}) +set_target_properties(test_move_arg_bp PROPERTIES LIBRARY_OUTPUT_DIRECTORY ${testdir} PREFIX "") diff --git a/tests/test_move_arg_bp.cpp b/tests/test_move_arg_bp.cpp new file mode 100644 index 0000000000..72cda73de9 --- /dev/null +++ b/tests/test_move_arg_bp.cpp @@ -0,0 +1,37 @@ +#include "test_move_arg.h" +#include +#include + +namespace py = boost::python; + +std::string item_repr(const Item& item) { + std::stringstream ss; + ss << "py " << item; + return ss.str(); +} + +void item_access(const Item& item) { + std::cout << "access " << item << "\n"; +} + +void item_access_ptr(const std::auto_ptr& item) { + std::cout << "access ptr " << item.get() << " "; + if (item.get()) std::cout << *item; + std::cout << "\n"; +} + +void item_consume(std::auto_ptr& item) { + std::cout << "consume " << *item << "\n "; + Item sink(std::move(*item.release())); + std::cout << " old: " << item.get() << "\n new: " << sink << "\n"; +} + +BOOST_PYTHON_MODULE(test_move_arg_bp) { + py::class_, boost::noncopyable>("Item", py::init()) + .def("__repr__", &item_repr); + + py::def("access", item_access); + py::def("access_ptr", item_access_ptr); + + py::def("consume", item_consume); +} diff --git a/tests/test_move_arg_bp.py b/tests/test_move_arg_bp.py new file mode 100644 index 0000000000..071827ee66 --- /dev/null +++ b/tests/test_move_arg_bp.py @@ -0,0 +1,27 @@ +import pytest +from test_move_arg_bp import Item, access, access_ptr, consume + + +def test(): + item = Item(42) + other = item + print(item) + access(item) + consume(item) + print("back in python") + + try: + access_ptr(item) + access(item) + except Exception as e: + print(e) + + del item + + try: + print(other) + except Exception as e: + print(e) + +if __name__ == "__main__": + test()