简体   繁体   中英

C extension for Python (Malloc)

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 )

Creating the previous example using SWIG is much more straight forward. To follow this path you need to get SWIG up and running first. To install it on an Ubuntu system, you might need to run the following commands

$ sudo apt-get install libboost-python-dev


$ sudo apt-get install python-dev

After that create two files. / hellomodule.c /

#include <stdio.h>

void say_hello(const char* name) {
    printf("Hello %s!\n", name);
}

/ hello.i /

%module hello extern void say_hello(const char* name);

Now comes the more difficult part, gluing it all together. First we need to let SWIG do its work.

swig -python hello.i

This gives us the files hello.py and hello_wrap.c . The next step is compiling (substitute /usr/include/python2.4/ with the correct path for your setup!).

gcc -fpic -c hellomodule.c hello_wrap.c -I/usr/include/python2.4/

Now linking and we are done!

gcc -shared hellomodule.o hello_wrap.o -o _hello.so

The module is used in the following way.

>>> import hello
>>> hello.say_hello("World")
Hello World!

if you want to use directly into IDE you can use http://cython.org/#about

and still if you want to develop your own, you may browse through source code of cython.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM