Kojumbo
Kojumbo

Reputation: 33

Problem with calling C function in Python

I want to call a function written in C via Python. For this task I've created three files in directory:

csquare.c
csquare.so
script.py

The file called csquare.c:

#include <stdio.h>
double math_square(double x) {
     return x*x;
 }

script.py:

import ctypes
import os

def Main():
    os.system('cc -fPIC -shared -o csquare.so csquare.c')
    so_path = str(os.getcwd()) + '/csquare.so'
    cfunctions = ctypes.CDLL(so_path)
    cfunctions.math_square.argtypes = [ctypes.c_double]

    print(cfunctions.math_square(90.0))

if __name__ == "__main__":
    Main()

The problem is that the program always prints "1". What am I doing wrong? If I change the type of math_square function to "int" everything works fine.

Thanks in advance

Upvotes: 3

Views: 64

Answers (1)

Niloct
Niloct

Reputation: 9995

This is missing in your python source:

cfunctions.math_square.restype = ctypes.c_double

The return type by default is ctypes.c_int:

https://docs.python.org/3/library/ctypes.html#return-types

Upvotes: 4

Related Questions