pybind11/example/example14.cpp

63 lines
2.2 KiB
C++
Raw Normal View History

2016-03-15 14:05:40 +00:00
/*
example/example14.cpp -- opaque types, passing void pointers
2016-03-15 14:05:40 +00:00
Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
2016-03-15 14:05:40 +00:00
All rights reserved. Use of this source code is governed by a
BSD-style license that can be found in the LICENSE file.
*/
#include "example.h"
#include <pybind11/stl.h>
#include <vector>
typedef std::vector<std::string> StringList;
2016-04-22 14:52:15 +00:00
class ClassWithSTLVecProperty {
public:
StringList stringList;
};
2016-04-28 14:25:24 +00:00
/* IMPORTANT: Disable internal pybind11 translation mechanisms for STL data structures */
PYBIND11_MAKE_OPAQUE(StringList);
2016-04-28 14:25:24 +00:00
2016-03-15 14:05:40 +00:00
void init_ex14(py::module &m) {
2016-04-28 14:25:24 +00:00
py::class_<StringList>(m, "StringList")
2016-03-15 14:05:40 +00:00
.def(py::init<>())
2016-04-28 14:25:24 +00:00
.def("pop_back", &StringList::pop_back)
/* There are multiple versions of push_back(), etc. Select the right ones. */
.def("push_back", (void (StringList::*)(const std::string &)) &StringList::push_back)
.def("back", (std::string &(StringList::*)()) &StringList::back)
.def("__len__", [](const StringList &v) { return v.size(); })
.def("__iter__", [](StringList &v) {
return py::make_iterator(v.begin(), v.end());
}, py::keep_alive<0, 1>());
2016-03-15 14:05:40 +00:00
2016-04-22 14:52:15 +00:00
py::class_<ClassWithSTLVecProperty>(m, "ClassWithSTLVecProperty")
.def(py::init<>())
2016-04-28 14:25:24 +00:00
.def_readwrite("stringList", &ClassWithSTLVecProperty::stringList);
2016-04-22 14:52:15 +00:00
2016-04-28 14:25:24 +00:00
m.def("print_opaque_list", [](const StringList &l) {
2016-04-22 14:52:15 +00:00
std::cout << "Opaque list: [";
bool first = true;
for (auto entry : l) {
if (!first)
std::cout << ", ";
std::cout << entry;
first = false;
}
std::cout << "]" << std::endl;
2016-03-15 14:05:40 +00:00
});
m.def("return_void_ptr", []() { return (void *) 0x1234; });
m.def("print_void_ptr", [](void *ptr) { std::cout << "Got void ptr : 0x" << std::hex << (uint64_t) ptr << std::endl; });
m.def("return_null_str", []() { return (char *) nullptr; });
m.def("print_null_str", [](char *ptr) { std::cout << "Got null str : 0x" << std::hex << (uint64_t) ptr << std::endl; });
m.def("return_unique_ptr", []() -> std::unique_ptr<StringList> {
StringList *result = new StringList();
result->push_back("some value");
return std::unique_ptr<StringList>(result);
});
2016-03-15 14:05:40 +00:00
}