Secure coding

Writing Python Compiled Modules

May 21, 2015 by

Any code that you write utilizing any compiled language like C, C++, or Java can be integrated or imported into another Python script. This code is considered as an "extension."

A Python extension module is nothing more than a C library. On UNIX machines, these libraries customarily end in .so (for shared object). On Windows machines, you typically optically discern .dll (for dynamically linked library).

Learn Secure Coding

Learn Secure Coding

Build your secure coding skills in C/C++, iOS, Java, .NET, Node.js, PHP and other languages.

Prerequisites for developing Extensions

To commence writing your extension, you are going to need the Python header files.

On UNIX machines, this customarily requires installing a developer-categorical package such as python2.5-dev.

Windows users get these headers as a component of the package when they utilize the binary Python installer.

Additionally, it is postulated that you have good understanding of C or C++ to write any Python Extension utilizing C programming.

The code needed to write the wrapper module is another C file containing a few special Python functions. Conventionally, the designations of C extensions commence with an underscore so let's call our module _chi2 and write it in a file _chi2.c (not to be confounded with the chi2.c file that we wrote just a minute ago).

In order to be able to access the C functions and types in the Python API, the first thing that we need to do is import the Python header.


#include <python.h>


Following is a simple definition of a Python script in a c wrapper:

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

Which takes argument in args variable which can be later on retrieved using PyArg_ParseTuple()

Before beginning to write a module, we need to specific Method Table and Initialization Function.

This function is called by the python interpreter during initialization phase

All this program does is initialize Python and then cleans it up. However, even a program as simple as this can be instructive. For one thing, unless you've already established Python for your C++ development environment, it shouldn't compile or link.

In order to get this program to build you require to have Python installed on your computer. Your computer may already have Python installed.

Once you have Python installed, you still need to get the headers apperceived by your compiler. I put the headers in a path so that they reside in the python/ virtual directory, which is additionally how the Python framework for Mac sets things up by default. This is in contrast with mundane Python elongating/embedding sources, which surmises that the Python headers are put in a place that you can access without a directory designation (i.e. #include in lieu of #include <Python/python.h>). For the purposes of this article the difference in directory structure is minor, since for the most part we will be including boost/python.hpp in lieu of the python.h header directly. You will withal need to integrate the Python lib directory to your linker path or otherwise directly integrate the Python library to your project (either pythonxy.lib, libpythonx.y.a or integrating the Python framework in OS X).

Additionally, in debug mode, with a default Python installation, the program will not link in MSVC. This is because the Python MSI installer comes with pythonxy.lib, but not the pythonxy_d.lib requested as an input file to the linker via a header program.

Writing a current stack frame and register display program.


1: A compiler for windows

2: Python 2.7 with SDK

Initialization of a python module:

Before beginning writing any module for python, a method table is called by the python interpreter . Which is of PyMethodDef type which has to be initialized using Py_InitModule


This class defines the functions called and included inside a compiled module.

Later on, this class can be initialized using

(void) Py_InitModule(MODULENAME, PyMethodDef);

When using python as an embedded program there is no need to define this method . In that case we can directly use Py_Initialize(0 API function to initialize the embeded program

void Py_Initialize();

lets name our module as PyPerf . In case of our example we can define our class as following.



#include <windows.h>

#include <python/python.h>

static PyObject *perf(PyObject *self, PyObject *args)


unsigned char *PerfRecord = (unsigned char*) malloc(sizeof(char) * 0x100);

int r1, r2, r3, r4, r5, r6, r7 , r8;



mov r1, eax

mov r2, ebx

mov r3 , ecx

mov r4 , edx

mov r5, edis

mov r6, esi

mov r7 , esp

mov r8 , ebp


sprintf(PerfRecord , "eax = %x, ebx = %x, ecx = %x, edi = %x, esi = %x, esp = %x, ebp = %x", r1, r2, r3, r4, r5, r6, r7, r8);

PyString_FromString((const char*)PerfRecord);


static PyMethodDef perfMethods[] = {

{"perf", perf, METH_VARARGS,
"Get all register information"},


PyMODINIT_FUNC initperf()

(void) Py_InitModule("perf", perfMethods);



HINSTANCE hinstDLL, // handle to DLL module

DWORD fdwReason, // reason for calling function

LPVOID lpReserved ) // reserved


// Perform actions based on the reason for calling.

switch( fdwReason )




// Return FALSE to fail DLL load.

// Do thread-specific initialization.



// Do thread-specific cleanup.



// Perform any necessary cleanup.



return 1; // Successful DLL_PROCESS_ATTACH.



Which can be compiled by specifying python27.lib and copy the file to python DLL directory. The module has to be named as mentioned in Python methods which in our case is perf.pyd

If we try to import the module we can see the method inside out module and calling the method returns a string consists of register information .

Learn Secure Coding

Learn Secure Coding

Build your secure coding skills in C/C++, iOS, Java, .NET, Node.js, PHP and other languages.


SecRat works at a start-up. He's interested in Windows Driver Programming.