~ubuntu-branches/ubuntu/precise/pyzmq/precise

« back to all changes in this revision

Viewing changes to zmq/utils/allocate.pxd

  • Committer: Bazaar Package Importer
  • Author(s): Piotr Ożarowski
  • Date: 2011-02-15 09:08:36 UTC
  • mfrom: (2.1.2 experimental)
  • Revision ID: james.westby@ubuntu.com-20110215090836-phh4slym1g6muucn
Tags: 2.0.10.1-2
* Team upload.
* Upload to unstable
* Add Breaks: ${python:Breaks}

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
"""A utility to allocate a C array.
 
2
 
 
3
This was copied from mpi4py and is licensed under the BSD license.
 
4
"""
 
5
 
 
6
from libc.stdlib cimport free, malloc
 
7
 
 
8
#-----------------------------------------------------------------------------
 
9
# Python includes.
 
10
#-----------------------------------------------------------------------------
 
11
 
 
12
cdef extern from "Python.h":
 
13
    object PyCObject_FromVoidPtr(void *, void (*)(void*))
 
14
 
 
15
#-----------------------------------------------------------------------------
 
16
# Main functions.
 
17
#-----------------------------------------------------------------------------
 
18
 
 
19
cdef inline void *memnew(size_t n):
 
20
    """malloc a new memory chunk of a given size."""
 
21
    if n == 0: n = 1
 
22
    return malloc(n)
 
23
 
 
24
cdef inline void memdel(void *p):
 
25
    """free a chunk of memory allocated with memnew."""
 
26
    if p != NULL: free(p)
 
27
 
 
28
cdef inline object allocate(size_t n, void **pp):
 
29
    """A wrapper that allocates a C array, but with Python ref-counting."""
 
30
    cdef object cob
 
31
    cdef void *p = memnew(n)
 
32
    if p == NULL:
 
33
        raise MemoryError()
 
34
    try:
 
35
        cob = PyCObject_FromVoidPtr(p, memdel)
 
36
    except:
 
37
        memdel(p)
 
38
        raise
 
39
    pp[0] = p
 
40
    return cob