[BUG] pickleable base C++ classes can incur object slicing if derived typeid is not registered with pybind11
Nobody has claimed this yet.
- Dominant language
- C++
- Stars
- 18k
- Forks
- 2.3k
- Avg merge
- 5d 17h
- Merged PRs (30d)
- 10
Description
Issue description
Context: https://github.com/pybind/pybind11/pull/2972#discussion_r658848867
If you have C++ base class that is exposed to pybind11, but then you have a derived class that is not exposed to pybind11, then you will encounter object slicing (wikipedia) via a pickle -> unpickle round trip.
Slicing may mean that the unpickled object has the wrong vtable, data, etc.
Reproducible example code
https://github.com/pybind/pybind11/compare/master...EricCousineau-TRI:issue-3062 (derived from fixes in #2972)
commit: https://github.com/pybind/pybind11/commit/7ce1ad059c58554453d42da3e9cd10cad978459a
Upon running the test:
$ make pytest
...
def test_roundtrip_simple_cpp_derived():
p = m.make_SimpleCppDerivedAsBase()
p.num = 404
assert m.get_value_via_vtable_cpp(p) == 10
...
data = pickle.dumps(p, pickle.HIGHEST_PROTOCOL)
p2 = pickle.loads(data)
assert isinstance(p2, m.SimpleBase)
assert p2.num == 404
> assert m.get_value_via_vtable_cpp(p2) == 10
E assert 1 == 10 # Egad! Error!
\cc @rwgk @YannickJadoul @elkhrt
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start with the linked reproducer and run make pytest, focusing on test_roundtrip_simple_cpp_derived and the make_SimpleCppDerivedAsBase and get_value_via_vtable_cpp entry points. Trace the pickle round trip for an exposed base with an unexposed derived type. Done means the unpickled object preserves the derived vtable behavior and passes the shown assertions.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- cpp, python
- Domain
- api, backend
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100