Getting Started with CPython: 2

Ononiwu IfeanyiOnoniwu Ifeanyi
2 min read

Hello reader,

The last article on CPython, we talked about calling a simple hello world function from a python script. Read about it here.

Let us talk about printing the attributes of a python list object as defined in C

Task: Print the number of items in a list object

Let's write the C program.

#include <stdio.h>
#include <Python.h>

void print_hello()
{
    printf("Hello, world!\n");
}

void printListSize(PyListObject *obj)
{
    PyObject *p = (PyObject *)obj;
    int size = PyList_Size(p);
    printf("No of items in List : %d\n", size);
}

hello.c


ii. Compile the C program. The compilation process is different now seeing we included the Python.h library

wisdom@ubuntu:~/text$ gcc -shared -Wl,-soname,hellolib.so -o hellolib.so -fPIC -I/usr/include/python3.10 hello.c

Compiling our c program into a dynamic library


iii. Now edit your main.py function to call the printListSize function in our C code

#!/usr/bin/python3
import ctypes
lib = ctypes.CDLL("./hellolib.so")

lib.print_hello()

lib.printListSize.argtypes = [ctypes.py_object]

my_list = [1, 2, 3, 4, 5]

lib.printListSize(my_list)

main.py


iv. Last step is to call our printlistSize function in our C library. If everything goes fine we should get the output below

wisdom@ubuntu:~/text$ python3 main.py 
Hello, world!
No of items in List : 5

That's all for now.

Keep in mind, you can also find some other attributes of a list apart from PyList_Size.

Other useful functions you can try are listed here.

Take care.

0
Subscribe to my newsletter

Read articles from Ononiwu Ifeanyi directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Ononiwu Ifeanyi
Ononiwu Ifeanyi