ITADN
PyO3/pyo3/Issues

pyo3-ffi: add missing `Py_SET_REFCNT` binding

#6306Closedxavierforge 创建于 19 天前
X
xavierforgecommented
While looking into #5487, I noticed a lingering `// TODO: Py_SET_REFCNT` in `refcount.rs` https://github.com/PyO3/pyo3/blob/166b043dc63616aca58d32c758368b4d25ac9e09/pyo3-ffi/src/refcount.rs#L149 Since this is the write counterpart to `ffi::Py_REFCNT` (read), and `pyo3-ffi` aims to mirror the C API, I would like to propose adding it. My proposal is to follow a structure similar to the existing `Py_REFCNT`/`Py_INCREF` implementations: - Declare `_Py_SetRefcnt` in `extern_libpython!` (it entered the stable ABI in Python [3.13](https://github.com/python/cpython/blob/9774b00f1dc05a53338620def6c4ab967d44159e/Misc/stable_abi.toml#L2495-L2497)). - Route both Limited API >= 3.13 and `Py_GIL_DISABLED` configurations to the function call, adopting the same "let the interpreter handle refcounting" pattern used in `Py_INCREF` (this also covers abi3t). - Provide an inline implementation for the remaining configurations: an immortal check + field write on Python 3.12+, and a plain field write for older versions. - Mirror the C header's `assert(refcnt >= 0)` with a `debug_assert!`, following existing precedent in this crate (e.g. `cpython/listobject.rs`). Also, unlike `Py_INCREF`, I suggest not leaving a performance `TODO` for the free-threaded build. `Py_SET_REFCNT` only appears in cold paths (object resurrection, test tooling), so reimplementing the BRC write logic would add maintenance cost (it needs the currently-skipped `_Py_IsOwnedByCurrentThread` and private flag constants) with no measurable benefit. For alternative interpreters: GraalPy exports `_Py_SetRefcnt` ([include/object.h L377](https://github.com/oracle/graalpython/blob/b0e680055f400623de5dc30a90ae61fb298590a0/graalpython/com.oracle.graal.python.cext/include/object.h#L377)), so it can route to the extern path like the GraalPy branch of `Py_REFCNT`. But PyPy has no `_Py_SetRefcnt` (consistent with `_Py_IncRef` being gated `not(PyPy)`) and falls into the plain field-write branch via its version cfgs. Please correct me if PyPy needs different handling. Happy to submit a PR if this sounds reasonable.
关闭于 18 天前 5 条评论