Getting Started with CPython : 1

It's not that scary

Hello reader,

It's the second sprint of the ALX-SE program and things are getting more interesting.

In the first sprint, most advanced tasks were mostly about 'crack-mes', now they are about CPython and then python bytecodes.

This article aims to give a sneak view into how to use CPython and also give fellow ALX-SE students who find this topic confusing somewhat of a foundation to build their knowledge.

The article will follow a practical viewpoint and won't go too much into too much technical jargon. That is to say, We will follow a problem-first approach.

Pre-requisites:

  • Little knowledge of C and Python programming language

  • Text editor

  • GCC compiler and Python installed on your computer

  • Passion to learn

Problem 1: Calling a C program from python.

Task: Write a C function that can be called from a python file to print hello world!

i. Let us first write the C function that prints hello world in a file named 'hello.c'

#include <stdio.h>

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

hello.c


ii. To call the print_hello function from a python script, the C file must first be compiled into a dynamic library. Let's assume python can access a C file that is first compiled into a dynamic library. Read more about dynamic libraries here.

To compile into a dynamic library use this command

$ gcc -fPIC -shared hello.c -o hellolib.so

compiling the hello.c file into a dynamic library named hellolib.so


iii. You should now have a file named hellolib.so in your working directory which is the dynamic library containing the print_hello function.

Next is to write our python file that calls the print_hello function.

#!/usr/bin/python3
import ctypes
lib = ctypes.CDLL("./hellolib.so")
"""
if the print_hello function had a parameter eg. name, an extra line would have been necessary like this.
---- lib.print_hello.argtypes = [ctypes.w_char_p]
refer here for other arg types = https://docs.python.org/3/library/ctypes.html
"""
lib.print_hello()

main.py


if everything goes well when you run the python program. It should give the expected output as shown below.

wisdom@ubuntu:~/text$ python3 main.py
Hello, world!

That is all for now.

Next article, we will look at how to print the attributes of a python list object eg. size allocated and type from a C program.

Take care.