Extending Python with ARMv7 Assembly
To complete the points delicáts project, my team was given the paramenters that any use of the Raspberry Pi’s GPIO must be done in ARMv7 assembly. For all other logic in the program, we were allowed to use our programming language of choice. Since the majority of the logic in our project was splicing language and dictionary lookups, python was an obvious, quick choice. Unlike C, however, python does not have a straightforward way to incorporate assembly inline. The more immediate solution would have been to simply use C/C++ as our language of choice, but not wanting to back down from a challenge, I looked for a way to embed assembly in python.
In a practical sense, this tutorial will not really add much to your repertoire. There is generally not much of a reason to drop down into assembly when working with python. If you really need the performance gains from dropping down to a low level, you will be much better off simply using C/C++ or any other compiled language with optimizations enabled. But, as programmers, sometimes we don’t do things because their best, but simply because we are curious on how they work.
tl:dr: To accomplish this tutorial, simply compile your assembly code as objects, add them as C bindings to your python project, and voilá, you will have ARMv7 assembly inside of your project!
Since this tutorial is focused on ARMv7 assembly, you will need to run any of this example code on a Raspberry Pi 3 or greater using a 32-bit Raspbian distro. If you are running 64-bit Raspbian, then you will need to write your Assembly code as ARMv8 rather than ARMv7. Since the examples here are not very complex, there will not be many differences between ARMv7 and ARMv8 code. How to program in ARMv7 is beyond the scope of this tutorial, but the code to follow will be provided.
Setting up a Python Package
Before going any further, let’s get our workspace set up. To do this, we are going to build a python package to handle and link all of our assembly code. Create a new directory for your project and use the following structure:
project_name\ |-- package | |-- arm | | |-- * asm files go here | |-- __init__.py | |-- setup.py |-- main.py
For example, my project folder looks like this:
Creating a function in ARMv7
To highlight how to do this, we will first need to begin by creating a couple of functions in ARMv7.