opaque<> clarifications

This commit is contained in:
Wenzel Jakob
2016-04-22 16:52:15 +02:00
parent 5a2924275c
commit 0871228f42
4 changed files with 78 additions and 14 deletions

View File

@@ -13,6 +13,11 @@
typedef std::vector<std::string> StringList;
class ClassWithSTLVecProperty {
public:
StringList stringList;
};
void init_ex14(py::module &m) {
py::class_<py::opaque<StringList>>(m, "StringList")
.def(py::init<>())
@@ -20,11 +25,24 @@ void init_ex14(py::module &m) {
.def("pop_back", [](py::opaque<StringList> &l) { l->pop_back(); })
.def("back", [](py::opaque<StringList> &l) { return l->back(); });
py::class_<ClassWithSTLVecProperty>(m, "ClassWithSTLVecProperty")
.def(py::init<>())
/* Need to cast properties to opaque types to avoid pybind11-internal
STL conversion code from becoming active */
.def_readwrite("stringList", (py::opaque<StringList> ClassWithSTLVecProperty:: *)
&ClassWithSTLVecProperty::stringList);
m.def("print_opaque_list", [](py::opaque<StringList> &_l) {
StringList &l = _l;
std::cout << "Opaque list: " << std::endl;
for (auto entry : l)
std::cout << " " << entry << std::endl;
std::cout << "Opaque list: [";
bool first = true;
for (auto entry : l) {
if (!first)
std::cout << ", ";
std::cout << entry;
first = false;
}
std::cout << "]" << std::endl;
});
m.def("return_void_ptr", []() { return (void *) 1234; });

View File

@@ -4,10 +4,13 @@ import sys
sys.path.append('.')
from example import StringList, print_opaque_list
from example import ClassWithSTLVecProperty
from example import return_void_ptr, print_void_ptr
from example import return_null_str, print_null_str
from example import return_unique_ptr
#####
l = StringList()
l.push_back("Element 1")
l.push_back("Element 2")
@@ -16,9 +19,21 @@ print("Back element is %s" % l.back())
l.pop_back()
print_opaque_list(l)
#####
cvp = ClassWithSTLVecProperty()
print_opaque_list(cvp.stringList)
cvp.stringList = l
cvp.stringList.push_back("Element 3")
print_opaque_list(cvp.stringList)
#####
print_void_ptr(return_void_ptr())
print(return_null_str())
print_null_str(return_null_str())
#####
print(return_unique_ptr())

View File

@@ -1,9 +1,8 @@
Opaque list:
Element 1
Element 2
Opaque list: [Element 1, Element 2]
Back element is Element 2
Opaque list:
Element 1
Opaque list: [Element 1]
Opaque list: []
Opaque list: [Element 1, Element 3]
Got void ptr : 1234
None
Got null str : 0