Re: C API and memory allocation
- From: "Gabriel Genellina" <gagsl-py2@xxxxxxxxxxxx>
- Date: Wed, 17 Dec 2008 22:42:17 -0200
En Wed, 17 Dec 2008 21:35:04 -0200, Floris Bruynooghe <floris.bruynooghe@xxxxxxxxx> escribió:
On Dec 17, 11:06 pm, Floris Bruynooghe <floris.bruynoo...@xxxxxxxxx>
wrote:
So I'm assuming PyArg_ParseTuple()
must allocate new memory for the returned string. However there is
nothing in the API that provides for freeing that allocated memory
again.
I've dug a little deeper into this and found that PyArg_ParseTuple
(and friends) end up using PyString_AS_STRING() (Python/getargs.c:793)
which according to the documentation returns a pointer to the internal
buffer of the string and not a copy and that because of this you
should not attempt to free this buffer.
Yes; but you don't have to dig into the implementation; from http://docs.python.org/c-api/arg.html :
s (string or Unicode object) [const char *]
Convert a Python string or Unicode object to a C pointer to a character string. You must not provide storage for the string itself; a pointer to an existing string is stored into the character pointer variable whose address you pass.
But how can python now know how long to keep that buffer object in
memory for?
It doesn't - *you* have to ensure that the original string object isn't destroyed (by example, incrementing its reference count as long as you keep the pointer), or copy the string contents into your own buffer.
--
Gabriel Genellina
.
- Follow-Ups:
- Re: C API and memory allocation
- From: Aaron Brady
- Re: C API and memory allocation
- References:
- C API and memory allocation
- From: Floris Bruynooghe
- Re: C API and memory allocation
- From: Floris Bruynooghe
- C API and memory allocation
- Prev by Date: Re: getting object instead of string from dir()
- Next by Date: Re: subprocess.Popen inheriting
- Previous by thread: Re: C API and memory allocation
- Next by thread: Re: C API and memory allocation
- Index(es):
Relevant Pages
|