Friday 28 March 2014

[tutorialspoint] Python Extension Programming with C

http://www.tutorialspoint.com/python/python_further_extensions.htm


For your first look at a Python extension module, you'll be grouping your code into four parts:
  • The header file Python.h.
  • The C functions you want to expose as the interface from your module.
  • A table mapping the names of your functions as Python developers will see them to C functions inside the extension module.
  • An initialization function

Structure
#include <Python.h>

static PyObject *module_func(PyObject *self, PyObject *args) {
   /* Do your stuff here. */
   Py_RETURN_NONE;
}

static PyMethodDef module_methods[] = {
   { "func", (PyCFunction)module_func, METH_NOARGS, NULL },
   { NULL, NULL, 0, NULL }
};

PyMODINIT_FUNC initModule() {
   Py_InitModule3(func, module_methods, "docstring...");
}
 

Example
#include <Python.h>

static PyObject* helloworld(PyObject* self)
{
    return Py_BuildValue("s", "Hello, Python extensions!!");
}

static char helloworld_docs[] =
    "helloworld( ): Any message you want to put here!!\n";

static PyMethodDef helloworld_funcs[] = {
    {"helloworld", (PyCFunction)helloworld, 
     METH_NOARGS, helloworld_docs},
    {NULL}
};

void inithelloworld(void)
{
    Py_InitModule3("helloworld", helloworld_funcs,
                   "Extension module example!");
}
 
 
Usage
setup.py

from distutils.core import setup, Extension
setup(name='helloworld', version='1.0',  \
      ext_modules=[Extension('helloworld', ['hello.c'])])

$ python setup.py install

Usage II
#!/usr/bin/python
import helloworld

print helloworld.helloworld()

No comments:

Post a Comment