Integrating C Code with Python

From PeformIQ Upgrade
Revision as of 15:07, 19 November 2008 by PeterHarding (talk | contribs)
Jump to navigation Jump to search

Overview

Examples

Simaple

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 sts;

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

    sts = system(command);

    return Py_BuildValue("i", sts);
}  // 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

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

references