Can't get pi from library c called from python using ctypes

I want to learn how to use python built-in ctypes module. I wrote simple c / C ++ code that returns pi multiples:

#define pi 3.14159265358979323846 //I tried this one too, not works.
double ppi(int n){
return n*3.14159265358979323846; //The same number multiplied by n
} 

      

I compiled it with MinGW with Code :: Blocks using the command

 gcc -shared -Wl,-soname,mylib.so -o mylib.so -fPIC mylib.c

      

I got a nice .so file and I tried to use it in python code:

 from ctypes import CDLL
 myModule=CDLL('mylib.so')
 print(myModule.ppi(1))
 print(myModule.ppi(2))

      

But it returns:

 2226964
 2226964

      

Any idea why this is happening? Thanks in advance!

+3


source to share


1 answer


From Return Types :

By default, it is assumed that the function returns the type of the C int

. Other return types can be specified by setting an attribute restype

on the function object.



So you have to do:

myModule.ppi.restype = c_double
print(myModule.ppi(1))
print(myModule.ppi(2))

      

+2


source







All Articles