Nov-03-2017, 03:10 PM
Hi, I have a question on the C extension. Please guide me if it's not the right place.
I wanted to add C methods into a pure python class, but I couldn't find any documentation on that.
After hours of hacking the python source, I finally succeeded to do that.
I attached a POC code for Python 2.7.
Can anyone comment on whether this kind of hack - implementing only a part of a class in C,
instead of implementing the whole class in C - will be likely supported on future Python versions?
* python source
class X(object):
pass
import x_ext
X().test(1)
* C extension
static PyObject *x_test(PyObject *self, PyObject *args)
{
puts("test");
PyObject_Print(args, stdout, 0);
puts("");
Py_RETURN_NONE;
}
PyMODINIT_FUNC initx_ext(void)
{
Py_InitModule("x_ext", NULL);
{
PyObject *type = PyDict_GetItemString(PyEval_GetGlobals(), "X");
static PyMethodDef test_def = {"test", (PyCFunction)x_test, METH_VARARGS, NULL};
PyObject *descr = PyDescr_NewMethod((PyTypeObject *)type, &test_def);
PyObject_SetAttrString(type, test_def.ml_name, descr);
Py_DECREF(descr);
}
}