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