[BUG]: Objects created using __new__ are not registered for casting

未关闭
#6,025 5 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

维护者通常 3 天内回复

还没有人认领这个 Issue。

评估

难度
4/5
预计耗时
3-5 天
新手友好度
45/100
Issue 类型
缺陷
描述清晰度
基本清楚
活跃度
冷清
技术栈
cpp, python

调研方向

首先构建可复现的 C++ pybind11 示例,并运行涉及 Num、MoreNum、new、mult2 和 mult4 的所示 Python 调用。跟踪通过 new 创建的 py::class_ 对象如何进入 pybind11 对象注册表;完成的标准是,这些对象已注册,并且链式调用保留实际的子类型行为。

由索引模型根据 Issue 内容生成。

描述

triage
Required prerequisites
What version (or hash if on master) of pybind11 are you using?

3.0.1

Problem description

When a pybind-based object or a subclass of one is created using new, it is not added to the registry of pybind objects for casting. If the object has methods than require casting to return the correct type information for its actual subtype, then this silently breaks those methods.

This is somewhat related to issue #1693, as using the listed workaround is how I found this problem.

Reproducible example code
Suppose we have:

#include <pybind11/pybind11.h>

using namespace py = pybind11;

struct Num {
    double n;
    Num(double n) : n(n) {}
    
    inline Num Mult2() { return Num(2 * n) }
}

PYBIND11_MODULE(this_example, m) {
    py::class_<Num> pyNum(m, "Num");

    pyNum
    .def(py::init([]() { return Num(0); }))
    .def("mult2", [](const Num *self) {
        py::object selfObj = py::cast(self);
        PyTypeObject *const ty = Py_TYPE(selfObj.ptr());
        auto newObj = py::reinterpret_steal<py::object>(ty->tp_new(ty, py::list().ptr(), py::dict().ptr()));
        *newObj.cast<Num*>() = self->Mult2();
        return newObj;
    })
    .def_readwrite("n", &Num::n);
}



from this_example import Num

class MoreNum(Num):
    def mult4(self):
        ret = self.__class__.__new__(self.__class__)
        ret.n = self.n * self.n
        return ret

# Works, but returned object is not registered.
MoreNum().mult2()
MoreNum().mult4()
MoreNum().mult2().mult4()

# mult4 is not implemented on Num
MoreNum().mult2().mult2().mult4()
Is this a regression? Put the last known working version here if it is.

Not a regression

主要语言
C++
星标
18k
派生
2.3k
平均合并
5 天 7 小时
30 天内合并 PR
53

环境准备

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

pybind/pybind11 的其他 Issue

查看 pybind/pybind11 的全部 Issue

相似的 Issue

更多 C++ Issue

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。