3

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

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.