python-3.x - 无法使用 ctypes 从 python 调用的 c 库中获取 pi

标签 python-3.x ctypes

我想了解如何使用 python 的内置 ctypes 模块。我写了一个简单的 c/c++ 代码,它返回圆周率的倍数:

#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
} 

我使用 Code::Blocks 使用命令使用 MinGW 编译它

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

我得到了一个可爱的 .so 文件并尝试在 python 代码中使用它:

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

但它返回:

 2226964
 2226964

知道为什么会这样吗? 提前致谢!

最佳答案

来自Return Types文档:

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.

所以你应该这样做:

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

关于python-3.x - 无法使用 ctypes 从 python 调用的 c 库中获取 pi,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27750904/

相关文章:

Python Ctypes 读取从 C++ dll 返回的 char*

python - 用 ctypes 包装 Python 中的 c 函数

python-3.x - Scikit learn/python 中自然文本的有效分类

python - 从 ctypes 访问公共(public) block 变量

python - ctypes 字符串指针类型错误

python - 使用 ctypes 在 Python 中解码 C const char*

python - 从边界生成移动物体

python - Pycryptodome 官方例子不清楚

python - OpenCV Python调整大小图像

python - 在指定时间内查找所有排列匹配