Calling a C library module with ctypes gives false results
Question: I created a simple C library file to test how I can access C functions with
ctypes.

The function in the C file named tetr.c reads:

    
    
    double square(double x){
        return x*x;
    }
    

So it returns the square of the number.

I've compiled it to an object file using the following:

    
    
    gcc -c tetr.c -o tetr.o
    

and to a shared object file using:

    
    
    gcc -shared -Wl,-soname,library.so -o tetr.so tetr.o
    

So far so good. I call the ipython shell, and set as the variable lib my
library:

    
    
    import ctypes
    lib = ctypes.cdll.LoadLibrary("tetr.so")
    

Naturally, when I'd call `lib.square(ctypes.c_double(2.0))` it should give me
`4.0`. Instead I get `1`. And same happens with any number I insert in the
function square, even zero.

A short notice, I used `ctypes.c_double` inside my function because without
that I get zero when I input an integer and

    
    
    ArgumentError: argument 1: <type 'exceptions.TypeError'>: Don't know how to convert parameter 1
    

when I input a float/double.

Any ideas of what I might be doing wrong?


Answer: You need to tell `ctypes` that the function returns a double. It can't figure
that out itself, so unless you tell it otherwise it assumes every function's
return type is `int`. See
<https://docs.python.org/2/library/ctypes.html#return-types>

For example:

    
    
    import ctypes
    lib = ctypes.cdll.LoadLibrary("tetr.so")
    lib.square.restype = ctypes.c_double
    ret = lib.square(ctypes.c_double(2.0))
    

