Unable to get name of derived class on C++ side
Nobody has claimed this yet.
- Dominant language
- C++
- Stars
- 18k
- Forks
- 2.3k
- Avg merge
- 5d 17h
- Merged PRs (30d)
- 10
Description
I have a class extendible in Python like this:
class Task_py : public Task_plugin {
public:
using Task_plugin::Task_plugin;
void set_id(int id) override {
auto class_name = py::cast(this).get_type().attr("__name__").cast<string>();
...
}
/* Trampoline (need one for each virtual function) */
void pre_process() override {
PYBIND11_OVERLOAD_PURE(void, Task_plugin,pre_process, );
}
void process_frame(const Frame_info& info) override {
PYBIND11_OVERLOAD_PURE(void, Task_plugin, process_frame, info );
}
void post_process(const Frame_info& info) override {
PYBIND11_OVERLOAD_PURE(void, Task_plugin, post_process, info);
}
...
py::class_<Task_plugin,Task_py,std::shared_ptr<Task_plugin>>(m, "Task_base"){
...
}
set_id() itself is not exposed and used internally to extract the name of derived class defined in Python on C++ side. This crashes with segfault on the .cast<string>(). py::cast(this).get_type().attr("__name__") works but then I can't convert it to string - it crashes whatever I do.
Interestingly, this works with no problems for simple classes:
class AA {
public:
void doit(){
auto class_name = py::cast(this).get_type().attr("__name__").cast<string>();
cout << class_name << endl; // Works with no problem
}
};
py::class_<AA>(m,"AA")
.def(py::init<>())
.def("doit",&AA::doit)
;
This works and prints class name.
What should I do get the name of derived class correctly?
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 by reproducing the reported difference between the simple AA class and the Task_plugin/Task_py trampoline using the snippets in the issue. Inspect the py::cast(this).get_type().attr("name") conversion path and determine why casting to C-string crashes for the derived class; done means identifying a safe supported approach or a minimal reproducible cause.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- cpp, python
- Domain
- api
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100