[Pyrex] Questions re: malloc and instance variables...

Adapted Cat a.c.junker at gmail.com
Mon Sep 25 12:20:56 UTC 2006


Hi,
  I'd like to wrap the C implementation of a 'class' in Python.
In C, I have a struct containing all the information about the
object, and functions that take pointers to such structs as
arguments. In Python, I'd like a class that holds an instance
variable, and functions in that class merely pass this variable
to their C counterparts. This works fairly well with:

------------
cdef class myclass:
  cdef void *my_struct

  def __init__(self, input):
    if type(input) is str:
      self.my_struct = <void *> struct_from_string(input)
------------

The main problem comes when I get another object of the
same class, e.g. for comparison or arithmetic operations.
I can access self.my_struct but not other.my_struct, as
Pyrex expects the latter to be a Python object - not a C
pointer. I can't make Pyrex recognize a class function as
returning other than a Python object, and I can't seem to
get a non-class function to take a Python object and
return a pointer to a struct, perhaps because the non-class
function has the same problem in that it believes that
var.my_struct is a Python object.
Is there any way around this?

Another problem arises because I'd like the initializer to
be able to take a list and convert it to a C array of ints or
longs before passing it to a similar struct_from_array()
function. The best I have so far is:

cdef extern from "stdlib.h"
  ctypedef int size_t
  cdef size_t sizeof(void *)
  cdef void *malloc(size_t)

...in __init__...
  if type(input) is list:
    cdef int *c_array
    cdef size_t c_size
    c_size = sizeof(int) * len(input)
    c_array = <int *> malloc(c_size)
    ................

Now I can't find where size_t and sizeof are actually defined.
sizeof is a macro I think, so won't be prototyped. This may
have something to do with the fact that I see malloc defined
in the generated C code as taking an 'int' despite the note in
the pyrex changelog (0.9.3) saying that typedefs are referred
to as their original typedef name. This code needs to work on
a variety of systems, and size_t can be 32, 48, or 64 bits long.

In the spirit of "batteries included" couldn't Pyrex just parse
  cdef int *c_array[len(input)]
and do its own memory allocation and garbage collection in the
generated C code? If not, is there a safe and portable way to
do mallocs in Pyrex code?

Thanks
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://lists.copyleft.no/pipermail/pyrex/attachments/20060925/ff7b9ed7/attachment.html 


More information about the Pyrex mailing list