Commit 88b17daa authored by frozar's avatar frozar
Browse files

[DEV] Add an example about binding C language and Python.

parent 3ea6b6b5
The customized example given here is inspired from :
https://docs.python.org/2/extending/extending.html
https://docs.python.org/2/extending/building.html
Description of directories:
- src: provide the source files written in C to build
the customised extension (module) to python. It directly
use the libpython-dev library.
- example: provide a tiny example file to use the customized module.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def usage( prog_name ):
print " Usage:", prog_name
print " Example:", prog_name
if __name__ == "__main__":
import sys
# Add the local installation directory of the demonstration spam module
lib_dir = sys.path[0] + '/../local/lib/python2.7/site-packages/'
sys.path = [lib_dir] + sys.path
try:
import spam
except ImportError:
print " FAIL: Cannot load the demonstration module spam."
print " hint: cd ../src ; make ; cd -"
exit( -1 )
spam.system('echo " SUCCESS: Loading spam module done."')
# if ( len( sys.argv[ 1: ] ) != 2 ):
# usage( sys.argv[ 0 ] )
# exit( 0 )
all: install_spammodule
build_spammodule: setup.py spammodule.c
python setup.py build
install_spammodule: setup.py spammodule.c
mkdir -p ../local
python setup.py install --prefix=../local
clean:
@rm -f *.so *.c *.mod *~
distclean:
@rm -rf ./build
@rm -rf ../local
from distutils.core import setup, Extension
module1 = Extension('spam',
sources = ['spammodule.c'])
setup (name = 'Spam',
description = 'Tiny example of customized extension python (written in C).',
version = '1.0',
author = 'Rozar Fabien',
author_email = 'fabien.rozar@umontpellier.fr',
url = 'https://docs.python.org/extending/building',
long_description = '''
This is really just a demo package.''',
license = 'LGPLv3',
platforms = 'any',
ext_modules = [Extension ('spam', ['spammodule.c'])] )
#include <Python.h>
#include <stdio.h>
#include <stdlib.h>
static PyObject *
spam_system(PyObject *self, PyObject *args);
static PyObject *SpamError;
static PyMethodDef SpamMethods[] = {
{"system", spam_system, METH_VARARGS,
"Execute a shell command."},
{NULL, NULL, 0, NULL} /* Sentinel */
};
PyMODINIT_FUNC
initspam(void)
{
PyObject *m;
m = Py_InitModule("spam", SpamMethods);
if (m == NULL)
return;
SpamError = PyErr_NewException("spam.error", NULL, NULL);
Py_INCREF(SpamError);
PyModule_AddObject(m, "error", SpamError);
}
static PyObject *
spam_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); */
if (sts < 0) {
PyErr_SetString(SpamError, "System command failed");
return NULL;
}
return PyLong_FromLong(sts);
}
// gcc spammodule.c -c $(pkg-config --libs --cflags python-2.7)
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment