Chapter 5. Python Extensions

Simplicity, carried to the extreme, becomes elegance.

Jon Franklin

The main objective of this chapter is to show you how you can extend Python to take advantage of existing binary library modules. Python provides a couple of ways to achieve this, and we’ll take a look at both of them.

Out of the box, Python cannot directly access the underlying hardware, nor can it interface directly with the software library modules provided by most hardware vendors. Python can, however, communicate with anything connected to a serial port or to a USB device that utilizes what is referred to as a virtual serial port (many USB–to–RS-485 converters use this technique). For those types of applications, an extension module typically isn’t necessary.

One way to give Python access to the real world, or just add some faster or specialized functionality, is to use the C programming language to create extensions. These are basically dynamically linked library (DLL) objects that give Python capabilities beyond what is included in its own libraries. We’ll mainly be using extensions as “wrappers” for the DLL modules supplied with commercial instruments and interfaces, but they might also be used to optimize a particular part of a Python program to improve on processing speed.

Another approach is to use Python’s ctypes library, which contains methods to directly access the functions in an external DLL. The ctypes library can be used directly from within a Python program without the ...

Get Real World Instrumentation with Python now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.