Re: C API and memory allocation



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

.



Relevant Pages

  • Re: This is getting really weird.
    ... I thought 4 bytes for reference count and 4 for string length. ... > There should be no memory allocation for that line. ... > manager may allocate more space than requested for its own efficiency. ... > that New returned with a pointer to the string constant. ...
    (alt.comp.lang.borland-delphi)
  • Re: [C++] Help!: map<userdefined*, vector<int>>
    ... >> The map will be sorted along pointer values. ... a constant string and as such has an address in memory. ... The only way to do that, if you used the very same memory ... >> and see if the sorted map output reflects that change. ...
    (alt.comp.lang.learn.c-cpp)
  • Re: Garbage collection
    ... I have not used Pinned memory so I cannot address that issue itself. ... IntPtr will be the correct size for a pointer on both 32Bit ... > I am using a MIDI header structure MIDIHDR. ... > The structure, an instance mhdr of the header, the string and its handle ...
    (microsoft.public.dotnet.languages.vb)
  • weird GCHandle behavior
    ... I need to pass the address of a variableto some win32 API functions like ... pointer to write data to the memory location. ... string to it, ...
    (microsoft.public.dotnet.languages.vb)
  • Re: Problem in writing structure to Binary file in C lang
    ... You allocate just enough memory ... to store a pointer, but rather likely not enough memory to store ... a string. ... pointer to a string then you write over memory yiu don't own. ...
    (comp.lang.c)