gpt4 book ai didi

python - 实现 nb_inplace_add 会导致返回只读缓冲区对象

转载 作者:行者123 更新时间:2023-12-01 05:57:11 25 4
gpt4 key购买 nike

我正在编写就地添加操作的实现。但是,由于某种原因,我有时会得到一个只读缓冲区作为结果(当我添加自定义扩展类和整数时......)。

相关代码为:

static PyObject *
ModPoly_InPlaceAdd(PyObject *self, PyObject *other)
{

if (!ModPoly_Check(self)) {
//Since it's in-place addition the control flow should never
// enter here(I suppose)
if (!ModPoly_Check(other)) {
PyErr_SetString(PyExc_TypeError, "Neither argument is a ModPolynomial.");
return NULL;
}
return ModPoly_InPlaceAdd(other, self);
} else {
if (!PyInt_Check(other) && !PyLong_Check(other)) {
Py_INCREF(Py_NotImplemented);
return Py_NotImplemented;
}
}

ModPoly *Tself = (ModPoly *)self;
PyObject *tmp, *tmp2;
tmp = PyNumber_Add(Tself->ob_item[0], other);
tmp2 = PyNumber_Remainder(tmp, Tself->n_modulus);

Py_DECREF(tmp);
tmp = Tself->ob_item[0];
Tself->ob_item[0] = tmp2;
Py_DECREF(tmp);
return (PyObject *)Tself;

}

如果我不是返回(PyObject*)Tself(或简单地“self”),而是引发异常,则原始对象会正确更新[使用一些printf进行检查]。如果我使用 Py_RETURN_NONE 宏,它会正确地将 ModPoly 转换为 None (在 python 端)。

我做错了什么?我正在返回一个指向 ModPoly 对象的指针,它如何成为缓冲区?我没有看到对这些指针进行任何操作。

用法示例:

>>> from algebra import polynomials
>>> pol = polynomials.ModPolynomial(3,17)
>>> pol += 5
>>> pol
<read-only buffer ptr 0xf31420, size 4 at 0xe6faf0>

我尝试将返回行更改为:

printf("%d\n", (int)ModPoly_Check(self));
return self;

并且在就地添加时打印1(这意味着返回的值是ModPolynomial类型...)

最佳答案

根据the documentation ,对象的就地添加操作返回一个新引用。

通过直接返回 self 而不调用 Py_INCREF ,您的对象将被释放,同时它仍然被引用。如果某个其他对象分配了同一 block 内存,那么这些引用现在将为您提供新对象。

关于python - 实现 nb_inplace_add 会导致返回只读缓冲区对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11897597/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com