Python logo on computer with Totalview logo and ctypes pointing to screen.
April 14, 2021

How to Debug Python in Mixed-Language Applications With Ctypes and TotalView

Debugging Best Practices

Python is one of the most widely used programming languages. It can be used to call other high level languages such as C, C++, and Fortran in order to provide access to high performance routines without having to rewrite existing code.

In this article we will answer the question "What is ctypes?" and learn how to debug a mixed language C/Python example using the ctypes framework.

Back to top

What Is Ctypes?

Ctypes is a foreign function library for Python. It provides C compatible data types, and allows calling functions in DLLs or shared libraries. It can be used to wrap these libraries in pure Python.

Debugging Example

The example calls a factorial function and returns the result. Here, we use Centos 7 and Python 2.7.

Steps

1. Start with a fact.c file for the factorial function.

/* File: fact.c */

int fact(int); 

int fact(int n) {
    if (n < 0) {
        return 0;
    }
    if (n == 0) {
        return 1;
    }
    else {
        return n * fact(n-1);
    }
}

2. Compile the fact.c file into a shared library called testfact.so.
$ gcc -g shared -Wl,-soname,testfact -o testfact.so -fPIC fact.c

3. Create a Python test program called testfactwrapper.py.

import ctypes
testfact = ctypes.CDLL('/home/stewart/Projects/Python/ctypes/fact/testfact.so')
num = 9
result = testfact.fact(num)

4. Test the Python wrapper.

Image showing testing of the Python wrapper.

5. Start the TotalView debugger to debug the application.

$ totalview -args python testfactwrapper.py

6. Set a pending breakpoint on the fact function.

Image of window showing breakpoint expression.

7. Press GO to debug the application.

Image of Totalview program. Select GO to debug.

8. After that, you will see the Python code debugged.

Image of Python code successfully debugged in TotalView.
Back to top

Further Reading

Watch a short tutorial Python in mixed-language applications with TotalView.

 

Debug With TotalView

Ready to try TotalView on your own? Sign up for a free trial.

TRY FREE

Back to top