test_opaque_types.cpp revision 11986:c12e4625ab56
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
14typedef std::vector<std::string> StringList;
15
16class ClassWithSTLVecProperty {
17public:
18    StringList stringList;
19};
20
21/* IMPORTANT: Disable internal pybind11 translation mechanisms for STL data structures */
22PYBIND11_MAKE_OPAQUE(StringList);
23
24test_initializer opaque_types([](py::module &m) {
25    py::class_<StringList>(m, "StringList")
26        .def(py::init<>())
27        .def("pop_back", &StringList::pop_back)
28        /* There are multiple versions of push_back(), etc. Select the right ones. */
29        .def("push_back", (void (StringList::*)(const std::string &)) &StringList::push_back)
30        .def("back", (std::string &(StringList::*)()) &StringList::back)
31        .def("__len__", [](const StringList &v) { return v.size(); })
32        .def("__iter__", [](StringList &v) {
33           return py::make_iterator(v.begin(), v.end());
34        }, py::keep_alive<0, 1>());
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    m.def("return_void_ptr", []() { return (void *) 0x1234; });
53    m.def("get_void_ptr_value", [](void *ptr) { return reinterpret_cast<std::intptr_t>(ptr); });
54    m.def("return_null_str", []() { return (char *) nullptr; });
55    m.def("get_null_str_value", [](char *ptr) { return reinterpret_cast<std::intptr_t>(ptr); });
56
57    m.def("return_unique_ptr", []() -> std::unique_ptr<StringList> {
58        StringList *result = new StringList();
59        result->push_back("some value");
60        return std::unique_ptr<StringList>(result);
61    });
62});
63