C Function Returns Integer Instead of Float - Python ctypes

Viewed 30

I have a very simple C program spammodule.c that looks like this:

#include <stdio.h>
#include <math.h>

float calculate_change(float previous, float current) {
    if (previous == current) {
        return 0;
    }
    float change;
    change = (current - previous) / previous;
    return change * 100.0;
};

Then I compile the program using gcc -fPIC -shared -o spammodule.so spammodule.c.

Then I import the compiled C program using ctypes and call this function from a python module main.py:

from ctypes import *

so_file = '/home/folder/spammodule.so'
main = CDLL(so_file)
print(main.calculate_change(c_float(100), c_float(200)))

This should return 100.00 which is the percentage change going from 100 to 200, but instead it prints 2 on console. Any suggestions on how to solve this?

1 Answers

From the Python ctypes documentation:

By default functions are assumed to return the C int type. Other return types can be specified by setting the restype attribute of the function object.

You don't set the restype attribute, so it's assumed that your function returns an int. In the same way that you have to explicitly set the types of parameters (with c_float(100)), you also have to explicitly set the return type.

Before the call to main.calculate_change, you should do the following:

main.calculate_change.restype = c_float
Related