实现nb_inplace_add会返回一个只读缓冲区对象 [英] Implementing nb_inplace_add results in returning a read-only buffer object

查看:101
本文介绍了实现nb_inplace_add会返回一个只读缓冲区对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm writing an implementation of the in-place add operation. But, for some reason, I sometimes get a read-only buffer as result(while I'm adding a custom extension class and an integer...).

相关代码为:

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端).

If instead of returning (PyObject*)Tself(or simply "self"), I raise an exception, the original object gets update correctly[checked using some printf]. If I use the Py_RETURN_NONE macro, it correctly turns the ModPoly into None (in the python side).

我做错了什么?我正在返回指向ModPoly对象的指针,这怎么能成为缓冲区?而且我看不到那些指针的任何操作.

What am I doing wrong? I'm returning a pointer to a ModPoly object, how can this become a buffer? And I don't see any operation on those pointers.

用法示例:

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

我尝试将返回线更改为:

I've tried change the return line into:

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

,并在原位添加时显示1(这意味着返回的值是ModPolynomial ...类型)

and it prints 1 when adding in-place (meaning that the value returned is of type ModPolynomial...)

推荐答案

根据文档,对象的就地添加操作将返回新的引用.

According to the documentation, the inplace add operation for an object returns a new reference.

通过直接返回self而不在其上调用Py_INCREF,您的对象将在仍被引用的同时被释放.如果为其他对象分配了相同的内存,则这些引用现在将为您提供新的对象.

By returning self directly without calling Py_INCREF on it, your object will be freed while it is still referenced. If some other object is allocated the same piece of memory, those references would now give you the new object.

这篇关于实现nb_inplace_add会返回一个只读缓冲区对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆