Integrating C Code with Python

From PeformIQ Upgrade
Jump to navigation Jump to search

Overview

This example was built under Linux...

Examples

Simple

Makefile

#---------------------------------------------------------------------

all:
        gcc -I /usr/local/include/python2.5 -fPIC -c test.c
        gcc -shared -o test.so test.o

#---------------------------------------------------------------------

clean:
        -/bin/rm -rf *.o

#---------------------------------------------------------------------

test.c

Note, on the system this demo was implemented on a version of Python 2.5 had been built from source and installed into /usr/local, so Python.h and other Python header files were located in /usr/local/include/python2.5/

#include "Python.h"

static PyObject *TestError;

//------------------------------------------------------------------------------

static PyObject* test_system(PyObject *self, PyObject *args);

//------------------------------------------------------------------------------

static PyMethodDef TestMethods[] = {
    {"system",  test_system, METH_VARARGS, "Execute a shell command."},
    {NULL, NULL, 0, NULL}        /* Sentinel */
};

//------------------------------------------------------------------------------

static PyObject *
test_system(PyObject *self, PyObject *args)
{
    const char *command;
    int status;

    if (!PyArg_ParseTuple(args, "s", &command))
        return NULL;

    status= system(command);

    return Py_BuildValue("i", status);
}  // test_system


//------------------------------------------------------------------------------

PyMODINIT_FUNC
inittest(void)
{
    PyObject *m;

    m = Py_InitModule("test", TestMethods);

    TestError = PyErr_NewException("test.error", NULL, NULL);

    Py_INCREF(TestError);

    PyModule_AddObject(m, "error", TestError);
}  // inittest

//------------------------------------------------------------------------------
[xxx]# make
gcc -I /usr/local/include/python2.5 -fPIC -c test.c
gcc -shared -o test.so test.o
[xxx]# python
Python 2.5.1 (r251:54863, Aug 17 2007, 11:25:00) 
[GCC 4.1.1 20061011 (Red Hat 4.1.1-30)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import test
>>> t = test.system('ls -l')
total 76
-rw-r--r-- 1 root root  638 Nov 19 15:12 dls.cpp
-rw-r--r-- 1 root root  134 Nov 19 15:13 hello.cpp
-rw-r--r-- 1 root root  333 Nov 19 16:03 Makefile
-rwxr-xr-x 1 root root 4204 Nov 19 14:35 Python__2_5.h
-rwxr-xr-x 1 root root 5301 Nov 19 15:24 spam.so
-rw-r--r-- 1 root root 1190 Nov 19 16:03 test.c
-rw-r--r-- 1 root root 1884 Nov 19 16:10 test.o
-rwxr-xr-x 1 root root 5301 Nov 19 16:10 test.so
>>> t
0
>>> 

references