Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C extension for Python (Malloc)

Tags:

python

c

I am writing C extension for python. All I want to do is to take size as input, create an object of that size and return the reference of that created object. My code looks like:

static PyObject *capi_malloc(PyObject *self, PyObject *args)
{
    int size;
    if (!PyArg_ParseTuple(args, "i", &size))
    return NULL;
    //Do something to create an object or a character buffer of size `size` 
    return something
}

How can I do this? I am able to allocate a memory using PyMem_Malloc() but confused about returning a reference of an object.

like image 422
Heisenberg Avatar asked Nov 11 '22 15:11

Heisenberg


1 Answers

If all you really want to do is to allocate a raw memory area of size size and return it, (even though it's not really a correctly initialized PyObject type), just do the following:

char *buf = (char *)PyMem_Malloc(size);
return (PyObject *)buf;

Not sure if that's useful in any way but it'll compile and get you a pointer to a raw memory buffer that's been cast as a PyObject pointer.

(This was not in your question but if you really want an honest to goodness PyObject pointer, you'll have to deal with calling something like PyObject_New() function. Docs here: http://docs.python.org/2/c-api/allocation.html )

like image 192
chetan Avatar answered Nov 15 '22 05:11

chetan