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.
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 )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With