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!
From the Return Types documentation:
By default functions are assumed to return the C
inttype. Other return types can be specified by setting therestypeattribute of the function object.
So you should do:
myModule.ppi.restype = c_double
print(myModule.ppi(1))
print(myModule.ppi(2))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With