defining class and subclass in C

Daniel Franke franke.daniel at gmail.com
Sat Jan 14 16:15:36 EST 2012


Hi all.

I spent some days and nights on this already and my google-fu is running out.

I'd like to implement the equivalent of this Python code in a C-extension:

>>> class A(object):
...  pass
>>> class B(A):
...  pass
>>> A
<class '__main__.A'>
>>> B
<class '__main__.B'>
>>> B.__bases__
(<class '__main__.A'>,)

However, loading my C-code (quoted below) I get:

>>> import ca
>>> ca
<module 'ca' from 'ca.so'>
>>> ca.ca
<type 'ca.ca'>

Here I'd expect "<class 'ca.ca'>" instead?! And I never managed a proper 
subclass :|

The point of the excercise: with "ca" and "cb" properly implemented, I'd like 
to subclass "cb" not from "ca", but from the Python "class A" - if possible?!

Could somepne kindly point out my mistake(s) and set me back on track?

Thanks

	Daniel

--
#include <Python.h>

typedef struct {
  PyObject_HEAD
} ca;

static PyTypeObject ca_Type = {
  PyObject_HEAD_INIT(NULL)
};

PyMODINIT_FUNC initca(void) {
  PyObject *ca;

  ca_Type.tp_name      = "ca.ca";
  ca_Type.tp_basicsize = sizeof(ca);
  ca_Type.tp_flags     = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE;

  if (PyType_Ready(&ca_Type) < 0)
    return;

  ca = Py_InitModule3("ca", NULL, "ca module");
  if (ca == NULL)
    return;

  Py_INCREF(&ca_Type);
  PyModule_AddObject(ca, "ca", (PyObject*)&ca_Type);
}

$ gcc -Wall -Wextra -g -fPIC -I/usr/include/python2.7 ca.c \
      -shared -Wl,-soname,ca.so -o ca.so -lpython2.7




More information about the Python-list mailing list