"Help needed - I don't understand how Python manages memory"

sturlamolden sturlamolden at yahoo.no
Sun Apr 20 16:19:43 EDT 2008


On Apr 20, 9:09 pm, "Hank @ITGroup" <hank.info... at gmail.com> wrote:

> Could you please give us some clear clues to obviously call python to
> free memory. We want to control its gc operation handily as we were
> using J**A.

If you want to get rid of a Python object, the only way to do that is
to get rid of every reference to the object. This is no different from
Java.

If you just want to deallocate and allocate memory to store text,
Python lets you do that the same way as C:


from __future__ import with_statement
import os
from ctypes import c_char, c_char_p, c_long, cdll
from threading import Lock

_libc = cdll.msvcr71 if os.name == 'nt' else cdll.libc
_lock = Lock()

def string_heapalloc(n):
    ''' allocate a mutable string using malloc '''
    with _lock:
        malloc = _libc.malloc
        malloc.argtypes = [c_long]
        malloc.restype = c_char * n
        memset = _libc.memset
        memset.restype = None
        memset.argtypes = [c_char * n, c_char, c_long]
        tmp = malloc(n)
        memset(tmp,'0',n)
    return tmp

def string_heapfree(s):
    ''' free an allocated string '''
    with _lock:
        free = _libc.free
        free.restype = None
        free.argtypes = [c_char_p]
        ptr_first_char = c_char_p( s[0] )
        free(ptr_first_char)


if __name__ == '__main__':
    s = string_heapalloc(1000)
    s[:26] = 'abcdefghijklmnopqrstuvwxyz'
    print s[:]
    string_heapfree(s)




More information about the Python-list mailing list