Python Further Extensions

Share on facebook
Share on twitter
Share on linkedin
Share on twitter
Share on tumblr

In this Python tutorial, let us discuss Python further extension modules with suitable examples.

Introduction of Python Extensions

Any language code such as C, C++ or Java that can be imported or combined into Python script. That code is called as an “Extension”.

A Python extension module is nothing more than a normal C library. On Unix machines, these libraries usually end in .so (for a shared object). On Windows machines, you typically see .dll (for a dynamically linked library)

To write Extension need Pre-Requisites

To start writing your extension, we need the Python header files.

  • This usually requires on Unix machines to install a developer-specific package such as python2.5-dev.
  • Windows users get these headers as part of the package when they use the binary Python installer.

Python.h – the header file

We need to include Python.h header file in the C source file that gives access to the internal Python API used to hook the module into an interpreter.

C Functions

The signatures of the C implementation of the functions always take one of the following three forms,

static PyObject *MyFunction( PyObject *self, PyObject *args );
static PyObject *MyFunctionWithKeywords(PyObject *self, PyObject *args, PyObject *kw);
static PyObject *MyFunctionWithNoArgs( PyObject *self );

The C functions are named by combining the Python module with function names together, as shown below

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

The Initialization Function

The last part of your extension module is the initialization function. This function is called by the Python interpreter when the module is loaded. It is required that the function be named initModule, where Module is the name of the module.

Structure

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

The description of Py_InitModule3 function as follows

  • func − This is the function to be exported.
  • module_methods − This is the mapping table name defined above.
  • docstring − This is the comment you want to give in your extension.

Example

#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(funcmodule_methods, "docstring...");
}

Leave a Comment

Your email address will not be published. Required fields are marked *