Skip to content

Commit f6c1df8

Browse files
committed
Adding check_dynamic_cast_SimpleCppDerived, related to issue #3062.
1 parent 5aa2e88 commit f6c1df8

File tree

2 files changed

+9
-2
lines changed

2 files changed

+9
-2
lines changed

tests/test_pickling.cpp

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -37,13 +37,13 @@ void wrap(py::module m) {
3737
.def(py::init<>())
3838
.def_readwrite("num", &SimpleBase::num)
3939
.def(py::pickle(
40-
[](const py::object& self) {
40+
[](const py::object &self) {
4141
py::dict d;
4242
if (py::hasattr(self, "__dict__"))
4343
d = self.attr("__dict__");
4444
return py::make_tuple(self.attr("num"), d);
4545
},
46-
[](const py::tuple& t) {
46+
[](const py::tuple &t) {
4747
if (t.size() != 2)
4848
throw std::runtime_error("Invalid state!");
4949
auto cpp_state = std::unique_ptr<SimpleBase>(new SimpleBaseTrampoline);
@@ -54,6 +54,9 @@ void wrap(py::module m) {
5454

5555
m.def("make_SimpleCppDerivedAsBase",
5656
[]() { return std::unique_ptr<SimpleBase>(new SimpleCppDerived); });
57+
m.def("check_dynamic_cast_SimpleCppDerived", [](const SimpleBase *base_ptr) {
58+
return dynamic_cast<const SimpleCppDerived *>(base_ptr) != nullptr;
59+
});
5760
}
5861

5962
} // namespace exercise_trampoline

tests/test_pickling.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,7 @@ def test_roundtrip_simple_py_derived():
6767

6868
def test_roundtrip_simple_cpp_derived():
6969
p = m.make_SimpleCppDerivedAsBase()
70+
assert m.check_dynamic_cast_SimpleCppDerived(p)
7071
p.num = 404
7172
if not env.PYPY:
7273
# To ensure that this unit test is not accidentally invalidated.
@@ -77,3 +78,6 @@ def test_roundtrip_simple_cpp_derived():
7778
p2 = pickle.loads(data)
7879
assert isinstance(p2, m.SimpleBase)
7980
assert p2.num == 404
81+
# Issue #3062: pickleable base C++ classes can incur object slicing
82+
# if derived typeid is not registered with pybind11
83+
assert not m.check_dynamic_cast_SimpleCppDerived(p2)

0 commit comments

Comments
 (0)