Pyrex: wrapping C struct as Python class

Duncan Booth duncan at NOSPAMrcp.co.uk
Thu Apr 10 12:38:31 EDT 2003


"Edward C. Jones" <edcjones at erols.com> wrote in 
news:b743fp$k40$1 at bob.news.rcn.net:

> In C code, I would use "malloc", "free" and "squareit" with Tiny. What 
> is the best way to wrap this in Pyrex so Python code can do
> 
>      t = Tiny(77)
>      print t.ival
>      print t.squareit()
>      del t
> 
> 
Wrapping the function is easy enough, but I think exposing the fields is a 
bit harder. Here is what I came up with:
(note minor corrections to your example)

----- tiny.h ----
typedef struct {
    int iVal;
} Tiny;

int squareit(Tiny *t);

----- tiny.c ----
#include "tiny.h"

int squareit(Tiny *t)
{
    return t->ival * t->ival;
}
----- pyTiny.pyx ----
cdef extern from "tiny.h":
        ctypedef struct c_Tiny "Tiny":
            int iVal

        cdef extern int c_squareit "squareit" (c_Tiny *t)

cdef class Tiny:
    cdef c_Tiny t

    def __init__(self, initial):
        self.t.iVal = initial

    def squareit(self):
        return c_squareit(&self.t)

    def __getattr__(self, name):
        if name=='iVal':
            return self.t.iVal
        return object.__getattribute__(self, name)

    def __setattr__(self, name, val):
        if name=='iVal':
            self.t.iVal = val
        else:
            object.__setattr__(self, name, val)
----- setup.py ---
from distutils.core import setup
from distutils.extension import Extension
from Pyrex.Distutils import build_ext

setup(
  name = 'Tiny',
  ext_modules=[ 
    Extension("pyTiny", ["pyTiny.pyx", "tiny.c"]),
    ],
  cmdclass = {'build_ext': build_ext}
)
----- test.py ---
from pyTiny import Tiny

t = Tiny(77)
print t.iVal
print t.squareit()
t.iVal = 66
print t.iVal
print t.squareit()
del t
---- phew! all done ---

-- 
Duncan Booth                                             duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?




More information about the Python-list mailing list