Python/C API question

Michael P. Reilly arcege at shore.net
Sat May 6 10:59:42 EDT 2000


User audun <audun at stud.cs.uit.no> wrote:
: I'm working on a Python module written in C, and I keep getting 
: impressed by Python's design and it's C/C++ API. However, I find the 
: "Python/C API Reference Manual" and the "Extending and embedding" 
: manuals weak on one point: The exact protocol in defining custom type 
: objects. My implementation has therefore been largely influenced by 
: the Python source code on these on this. There is one detail I'd like 
: to ask about.

You might want to also read "How to write a Python Extension" (<URL:
http://starship.python.net/crew/arcege/extwriting/pyext.html>, as yet
still uncompleted).

: Let's say I've constructed (in C) a Python object of type ekkiekki. In 
: the file ekkiekki.c I've defined the methods associated with the object 
: in a PyMethodDef structure that is used by ekkiekki's setattr and 
: getattr functions. Furthermore, let's imagine that the method static 
: PyObject * tapang(self, args) is such a method associated with ekkiekki. 
: My question is then: Is it wise and/or necessary to do any type checking 
: on the self-argument in such built-in methods (as in calling a 
: Ekkiekki_Check(self))? And what about setattr/getattr and the other 
: "basic" methods defined in ekkiekki's PyTypeObject-structure? Does the 
: interpreter make any guarantees about "who" being able to call an 
: object's internal methods?

You do not necessarily have to check the type, but it is a quick check
(comparing two pointers).  The interpreter will deal with most all of this
for you.  The issue will be that the function prototype will want to be
PyObject *self, but your object will be ekkiekki.  One suggestion is to
add a local variable that casts the value for you:
  PyObject *function(PyObject *self, PyObject *self)
    { ekkiekki *object = (ekkiekki *)self;

I prefer to make macros to access the fields in the structure:
  #define ekkiekki_fieldname(obj) (((ekkiekki *)(obj))->fieldname)
Do this for each field you will want to access.

  -Arcege




More information about the Python-list mailing list