calling Pyrex results from C

Greg Ewing (using news.cis.dfn.de) g2h5dqi002 at sneakemail.com
Wed Feb 11 19:58:38 EST 2004


Kyler Laird wrote:
> 	cdef public char* string(x):
> 		s = str(x)
> 		return(s)

Whenever you allow Pyrex to coerce a Python string into a
char *, you need to be careful that the Python string will
remain alive for as long as the C pointer is needed.

In this case, str(x) is probably returning a string with
no other references, so it's deallocated as soon as the
function finishes, and a dangling pointer is then returned.

You'll need to make a copy of the string's contents
somehow, e.g.

   cdef extern from "string.h":
     char *strcpy(char *)

   cdef public char* string(x):
     s = str(x)
     return strcpy(s)

and remember to free() it when you're finished with
it.

(Warning: Don't try to write it as

     return strcpy(str(x)) # WRONG

or you'll have the same problem -- the string will
be deallocated before strcpy() gets a chance to
copy it!)

Some other comments:

* In the C code, it's better to declare pointers to
Python objects as PyObject * rather than void *, e.g.

   PyObject *im, *im_size;

since this will give you better type checking from the
C compiler.

* Your C code as written leaks Python objects, since it
never decrefs the objects returned by image_file_open
and image_size.It also doesn't do anything about checking
for and handling Python exceptions.

It's much better if you can do all creation and manipulation
of Python objects in Pyrex, since it takes care of
refcounting and error checking automatically (although
read the doc section on Error Return Values to make sure
exceptions are propagated from functions that don't
return Python objects).

You may want to put something in your main function to
catch exceptions and print a traceback, since that
won't happen automatically with no Python interpreter
at the top level.

-- 
Greg Ewing, Computer Science Dept,
University of Canterbury,	
Christchurch, New Zealand
http://www.cosc.canterbury.ac.nz/~greg




More information about the Python-list mailing list