You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

62 lines
2.2 KiB

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