return best representation of polymorphic types (fixes #105)

This commit is contained in:
Wenzel Jakob
2016-04-13 13:45:09 +02:00
parent d40885a1e6
commit d7efa4ff7b
7 changed files with 55 additions and 4 deletions

View File

@@ -24,6 +24,7 @@ void init_ex12(py::module &);
void init_ex13(py::module &);
void init_ex14(py::module &);
void init_ex15(py::module &);
void init_ex16(py::module &);
void init_issues(py::module &);
PYBIND11_PLUGIN(example) {
@@ -44,6 +45,7 @@ PYBIND11_PLUGIN(example) {
init_ex13(m);
init_ex14(m);
init_ex15(m);
init_ex16(m);
init_issues(m);
return m.ptr();

24
example/example16.cpp Normal file
View File

@@ -0,0 +1,24 @@
/*
example/example16.cpp -- automatic upcasting for polymorphic types
Copyright (c) 2015 Wenzel Jakob <wenzel@inf.ethz.ch>
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"
struct BaseClass { virtual ~BaseClass() {} };
struct DerivedClass1 : BaseClass { };
struct DerivedClass2 : BaseClass { };
void init_ex16(py::module &m) {
py::class_<BaseClass>(m, "BaseClass").def(py::init<>());
py::class_<DerivedClass1>(m, "DerivedClass1").def(py::init<>());
py::class_<DerivedClass2>(m, "DerivedClass2").def(py::init<>());
m.def("return_class_1", []() -> BaseClass* { return new DerivedClass1(); });
m.def("return_class_2", []() -> BaseClass* { return new DerivedClass2(); });
m.def("return_none", []() -> BaseClass* { return nullptr; });
}

12
example/example16.py Normal file
View File

@@ -0,0 +1,12 @@
from __future__ import print_function
import sys
sys.path.append('.')
from example import return_class_1
from example import return_class_2
from example import return_none
print(type(return_class_1()))
print(type(return_class_2()))
print(type(return_none()))

3
example/example16.ref Normal file
View File

@@ -0,0 +1,3 @@
<class 'example.DerivedClass1'>
<class 'example.DerivedClass2'>
<type 'NoneType'>