Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot get pi from a c library called from python using ctypes

I want to discover how to use the python's built-in ctypes module. I wrote a simple c/c++ code which returns pi's 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 the MinGW came with the Code::Blocks using the command

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

I got a cute .so file & I tried to use it in a 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 it happens? Thanks in advance!

like image 942
Sasszem Avatar asked Apr 21 '26 04:04

Sasszem


1 Answers

From the Return Types 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.

So you should do:

myModule.ppi.restype = c_double
print(myModule.ppi(1))
print(myModule.ppi(2))
like image 129
Barmar Avatar answered Apr 23 '26 03:04

Barmar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!