C API and memory allocation

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Wed Dec 17 20:28:04 EST 2008


En Wed, 17 Dec 2008 22:51:03 -0200, Aaron Brady <castironpi at gmail.com>  
escribió:
> On Dec 17, 6:42 pm, "Gabriel Genellina" <gagsl-... at yahoo.com.ar>
> wrote:
>> En Wed, 17 Dec 2008 21:35:04 -0200, Floris Bruynooghe  
>> <floris.bruynoo... at gmail.com> escribió:

>> > 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.
>
> I missed something.  How did you get a reference to the original
> string object, with which to increment its reference count?

 From the original arguments to the function -- the first argument you pass  
to  PyArg_ParseTuple &co.

> How do
> you know its length to copy it into your own buffer?

Use the "s#" format instead, which returns both a pointer to the string  
contents and its length. Even if you're not going to copy the buffer, it's  
required in case the string could contain any NUL byte.

-- 
Gabriel Genellina




More information about the Python-list mailing list