Executing C code from Python on Linux (Petalinux) on ZCU102
In this simple demo, I will be showing how to configure the Petalinux to enable Python and the ctypes and cffi python packages and testing a simple demo.
Creating the Petalinux Image:
petalinux
petalinux-create -t project -s <path to bsp>.bspOpen the project-spec\meta-user\recipes-core\images\petalinux-image.bbappend and add the Python packages below:
packages
IMAGE_INSTALL_append = " python-cffi"
IMAGE_INSTALL_append = " python-pycparser"
IMAGE_INSTALL_append = " libffi"Next, return to the console and add the python packages to the rootfs:
rootfs
cd <plnx proj>
petalinux-config -c rootfs
Filesystem Packages -> devel -> python -> python -> [*] python
[*] python-shell
[*] python-io
[*] python-distutils
[*] python-ctypes
user packages -> [*] python-cffi
[*] python-pycparser
[*] libffiFinally, to build:
build
petalinux-build
cd images/linux
petalinux-package --boot --fpga system.bit --u-bootBuilding C code shared object:
First, we need to create a shared library (.so) file. Here, I have a simple function that I used:
fib
int fib(int a) {
if(a <= 0)
return -1;
else if (a == 1)
return 0;
else if ((a==2) || (a==3))
return 1;
else
return fib(a-2) + fib(a-1);
}Compile:
compile
aarch64-linux-gnu-gcc -c -fPIC fib.c
aarch64-linux-gnu-gcc -shared -o libfib.so fib.oNext, create the Simple Python script utilizing the ctypes to call this shared library:
ctypes
import ctypes
libfib=ctypes.CDLL('./libfib.so')
fib = libfib.fib(10)
print "Fib: ", fibNote: the script here assumes that the libfib.so is in the same directory as the python script. In relaity this would be in /usr/lib
Test on Hardware:
Boot the board, and setup the LAN:
ifconfig
ifconfig eth0 192.168.1.2ctypes:
Then run the ctypes_fib.py script:
cffi:
Next, create the Simple Python script utilizing the cffi to call this shared library:
cffi
from cffi import FFI
ffi = FFI()
ffi.cdef("""int fib(int n);""")
libfib = ffi.dlopen("./libfib.so")
print libfib.fib(10)Copy this to the board, and execute:
© 2025 Advanced Micro Devices, Inc. Privacy Policy