Hi, recently I needed to use weakrefs and found them a bit awkward because they need to accept a python function when that function is (usually/always?) a C function.
Heres an example of a weakref callback in C...
Anyone know if theres a nicer way to use PyCFunction_New, rather then define a PyMethodDef beforehand?
Id prefer if you could just pass the C function as the weakref callback, perhaps it would be possible to have an alternate PyWeakref_NewProxy function that accepted a C function as a callback.
heres the weakref callback method I used....
/* c function*/ PyObject * arm_weakref_callback_weakref_dealloc(PyObject *self, PyObject *weakref); /* python callable */ PyObject * arm_weakref_callback_weakref_dealloc__pyfunc;
/* internal func to remove weakref from weakref list */ PyObject * arm_weakref_callback_weakref_dealloc(PyObject *self, PyObject *weakref) { char *list_name = ARM_WEAKREF_LIST_NAME; PyObject *maindict = NULL, *armlist = NULL; int i; /* error checking below removed */ maindict= PyModule_GetDict(PyImport_AddModule( "__main__")); armlist = PyDict_GetItemString(maindict, list_name); i = PySequence_Index(armlist, weakref); PySequence_DelItem(armlist, i); Py_RETURN_NONE; }
PyObject *Armature_CreatePyObject(struct bArmature *armature) {
/* snip----- */
weakref = PyWeakref_NewProxy((PyObject*)py_armature,
arm_weakref_callback_weakref_dealloc__pyfunc);
/* snip----- */
return (PyObject *) py_armature;
}
/* internal use only */ static PyMethodDef bpy_arm_weakref_callback_weakref_dealloc[] = { {"arm_weakref_callback_weakref_dealloc", arm_weakref_callback_weakref_dealloc, METH_O, ""} };
//-------------------MODULE INITIALIZATION-------------------------------- PyObject *Armature_Init(void) { /* snip----- */ arm_weakref_callback_weakref_dealloc__pyfunc = PyCFunction_New(bpy_arm_weakref_callback_weakref_dealloc, NULL); /* snip----- */
}
-- Campbell J Barton (ideasman42)
participants (1)
-
Campbell Barton