I finally figured out how to implement classes in Python using C API — the right way. Namely as a new type using the PyTypeObject complete with get and set attribute calls and plain members. But I tought my previous hack for building a class at runtime is still slim enough to share, especially if you just got a couple of methods that you want bundled into a class instead of a module.
The following function is very similar to the Py_InitModule(char*, PyMethodDef*) except that it returns a class object instead of a module object. Remember that the first argument to your methods will be an instance object of the class, and that you can include a method named __init__ just like in any regular Python class definition.
- inline PyObject*
- Py_InitClass(char* Name, PyMethodDef* Methods)
- {
- PyObject* classDict = PyDict_New();
- PyObject* className = PyString_FromString(Name);
- PyObject* classObject = PyClass_New(NULL, classDict, className);
- PyMethodDef* def;
- for (def = Methods; def->ml_name != NULL; def++)
- {
- PyObject* func = PyCFunction_New(def, NULL);
- PyObject* method = PyMethod_New(func, NULL, classObject);
- PyDict_SetItemString(classDict, def->ml_name, method);
- }
- return classObject;
- }
Post a comment