Skip to content

Commit

Permalink
working boost::python example
Browse files Browse the repository at this point in the history
  • Loading branch information
rhaschke committed Dec 23, 2019
1 parent 98ea003 commit 6cfebdc
Show file tree
Hide file tree
Showing 3 changed files with 70 additions and 0 deletions.
6 changes: 6 additions & 0 deletions tests/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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 "")
37 changes: 37 additions & 0 deletions tests/test_move_arg_bp.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
#include "test_move_arg.h"
#include <boost/python.hpp>
#include <sstream>

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>& item) {
std::cout << "access ptr " << item.get() << " ";
if (item.get()) std::cout << *item;
std::cout << "\n";
}

void item_consume(std::auto_ptr<Item>& 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_<Item, std::auto_ptr<Item>, boost::noncopyable>("Item", py::init<int>())
.def("__repr__", &item_repr);

py::def("access", item_access);
py::def("access_ptr", item_access_ptr);

py::def("consume", item_consume);
}
27 changes: 27 additions & 0 deletions tests/test_move_arg_bp.py
Original file line number Diff line number Diff line change
@@ -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()

0 comments on commit 6cfebdc

Please sign in to comment.