test_opaque_types.cpp revision 12391:ceeca8b41e4b
1/* 2 tests/test_opaque_types.cpp -- opaque types, passing void pointers 3 4 Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch> 5 6 All rights reserved. Use of this source code is governed by a 7 BSD-style license that can be found in the LICENSE file. 8*/ 9 10#include "pybind11_tests.h" 11#include <pybind11/stl.h> 12#include <vector> 13 14using StringList = std::vector<std::string>; 15 16/* IMPORTANT: Disable internal pybind11 translation mechanisms for STL data structures */ 17PYBIND11_MAKE_OPAQUE(StringList); 18 19TEST_SUBMODULE(opaque_types, m) { 20 // test_string_list 21 py::class_<StringList>(m, "StringList") 22 .def(py::init<>()) 23 .def("pop_back", &StringList::pop_back) 24 /* There are multiple versions of push_back(), etc. Select the right ones. */ 25 .def("push_back", (void (StringList::*)(const std::string &)) &StringList::push_back) 26 .def("back", (std::string &(StringList::*)()) &StringList::back) 27 .def("__len__", [](const StringList &v) { return v.size(); }) 28 .def("__iter__", [](StringList &v) { 29 return py::make_iterator(v.begin(), v.end()); 30 }, py::keep_alive<0, 1>()); 31 32 class ClassWithSTLVecProperty { 33 public: 34 StringList stringList; 35 }; 36 py::class_<ClassWithSTLVecProperty>(m, "ClassWithSTLVecProperty") 37 .def(py::init<>()) 38 .def_readwrite("stringList", &ClassWithSTLVecProperty::stringList); 39 40 m.def("print_opaque_list", [](const StringList &l) { 41 std::string ret = "Opaque list: ["; 42 bool first = true; 43 for (auto entry : l) { 44 if (!first) 45 ret += ", "; 46 ret += entry; 47 first = false; 48 } 49 return ret + "]"; 50 }); 51 52 // test_pointers 53 m.def("return_void_ptr", []() { return (void *) 0x1234; }); 54 m.def("get_void_ptr_value", [](void *ptr) { return reinterpret_cast<std::intptr_t>(ptr); }); 55 m.def("return_null_str", []() { return (char *) nullptr; }); 56 m.def("get_null_str_value", [](char *ptr) { return reinterpret_cast<std::intptr_t>(ptr); }); 57 58 m.def("return_unique_ptr", []() -> std::unique_ptr<StringList> { 59 StringList *result = new StringList(); 60 result->push_back("some value"); 61 return std::unique_ptr<StringList>(result); 62 }); 63} 64