CPython - How to create and add a method attribute to an object with __dict__?

社会主义新天地 提交于 2019-12-02 18:21:08

问题


This can be a tricky question...

In short I am creating and adding a method as follows:

static PyObject *ret_arg(PyBVHTree *self, PyObject *arg)
{
    /* just to demonstrate */
    return arg;
}
static PyMethodDef my_meth = {"ret_arg", (PyCFunction)ret_arg, METH_O, 0};       

...
    PyObject* func = PyCFunction_New(&my_meth, my_object);
    Py_DECREF(my_object);
    PyObject_SetAttrString(my_object, "ret_arg", func);
    Py_DECREF(func);
    return my_object;
}

It works! But having some problems :(

eg.:

  • If I del my_object. And use the new method, CRASH.
  • When I close the program with python. Error: EXCEPTION_ACCESS_VIOLATION. And this is no problem with refcount

So my question is:

What is the correct way to do this?

来源:https://stackoverflow.com/questions/35835421/cpython-how-to-create-and-add-a-method-attribute-to-an-object-with-dict

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!