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-create -t project -s <path to bsp>.bsp
Open the project-spec\meta-user\recipes-core\images\petalinux-image.bbappend and add the Python packages below:
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:
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 [*] libffi
Finally, to build:
petalinux-build cd images/linux petalinux-package --boot --fpga system.bit --u-boot
Building C code shared object:
First, we need to create a shared library (.so) file. Here, I have a simple function that I used:
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:
aarch64-linux-gnu-gcc -c -fPIC fib.c aarch64-linux-gnu-gcc -shared -o libfib.so fib.o
Next, create the Simple Python script utilizing the ctypes to call this shared library:
import ctypes libfib=ctypes.CDLL('./libfib.so') fib = libfib.fib(10) print "Fib: ", fib
Note: 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 eth0 192.168.1.2
ctypes:
Then run the ctypes_fib.py script:
cffi:
Next, create the Simple Python script utilizing the cffi to call this shared library:
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:
© Copyright 2019 - 2022 Xilinx Inc. Privacy Policy