pybind / pybind/pybind11

py::cast variant using type_info instead of template argument for non-virtual types.

Open
#1,158 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
C++
Stars
18k
Forks
2.3k
Avg merge
5d 17h
Merged PRs (30d)
10

Description

Issue description

It would be a nice feature to have a non-template casting function using type_info for non-virtual types.
I gather pybind11 for static-types binds the type_info to the first export of the type by ptr (if it was a Base it gets locked in Base, if it was a Derived stays a Derived, etc)

I made a workaround by accessing the detail part of pybind, so I guess it could change eventually.

Use case

In C++ I have dynamic-bound factories wrappers like
Base *Create( int id )
T *Create<T>() { return static_cast<T*>(Create( id_map[typeid(T)] )); }.

To avoid having to make one py-binding for each type (non-scalable), I export a
py::object Create(int id)
that changes the return type according to a type_info.

Setup

pybind11 2.2.1

Example code

DIRECT TYPE
py::object castComponentByTypeInfo(Base *src, const std::type_info &type) {
	using T1 = pybind11::detail::type_caster_generic;

	auto &st = T1::src_and_type(src, type, nullptr);
	assert(st.second != nullptr);

	auto handle = T1::cast(
		st.first, py::return_value_policy::reference, {}, st.second,
		nullptr, nullptr
	);
	return py::reinterpret_borrow<py::object>(handle);
}
HELD TYPE
py::object castComponentByTypeInfo(holder<Base> src, const std::type_info &type) {
	using T1 = pybind11::detail::type_caster_generic;

	auto &st = T1::src_and_type(src.get(), type, nullptr);
	assert(st.second != nullptr);

	auto handle = T1::cast(
		st.first, py::return_value_policy::take_ownership, {}, st.second,
		nullptr, nullptr, &src);

	return py::reinterpret_steal<py::object>(handle);
}

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reading pybind11's detail::type_caster_generic, especially src_and_type and cast, and compare the direct and held-type examples in the issue. Determine the public API needed for a non-template type_info cast for non-virtual types, then verify that both ownership cases produce the requested Python object without relying on private detail internals.

Written by the indexing model from the issue text.

Assessment

Tech stack
cpp, python
Domain
backend-api-design
Issue type
Feature
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.