[Pyrex] Total newbie needs code review

Grant McDonald gmcdonald at infocomp.com
Mon Sep 12 01:20:23 CEST 2005


Chris,

What pyrex means by "Obtaining char * from temporary Python value" is that
you haven't created a char pointer variable to hold the string value. When
this happens pyrex needs to create a temporary variable to hold the value
returned by the Python/C API call PyString_AsString. The way to remove this
warning from your code is to be explicit in your conversions:

cdef void doStuff(char * stuff)
	sprintf("this is stuff: %s\n", stuff)


cdef char * cStuff
pyStuff = "this is stuff"

doStuff(pyStuff)	# implicit


cStuff = pyStuff
doStuff(cStuff) 	# explicit


As i mentioned before the assignment of pyStuff to cStuff or the implicit
function call both obtain a pointer that refers to the internal buffer of
the python object not a copy, so it mustn't be modified. An example of a
modifying function:

cdef void modifyArg(char * stuff)
	strcat(stuff, " and more stuff!")

So if you are passing in the pointer reference as an argument to a function
you must be totally sure that the function does not modify it in _any_ way.
If you can't be sure malloc a char pointer to the size of the string and
strcpy the contents of the pystring into it:

cdef char * copy
pyString = "a python string!"

# malloc char pointer; len + 1 for null terminator
copy = <char *>PyMem_Malloc(len(pyString) * sizeof(char) + 1)

# this implicit conversion is fine since strcpy does not modify the src
strcpy(copy, pyString)

# do something with copy that modifies it
modifyArg(copy)

# free memory
PyMem_Free(copy)

In the above example I have used the PyMem_* routines which are defined in
the python header file. Have a look in the Python/C API reference for a
definition and description of them. Please ensure that whatever memory you
malloc you free, since the python interpreter will not automatically free
memory allocated outside the interpreter.

Regards,

Grant M.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://lists.copyleft.no/pipermail/pyrex/attachments/20050912/53a820a0/attachment.html


More information about the Pyrex mailing list