我们可以使用 Python 程序调用 C 函数ctypes module.
它涉及以下步骤:
- 创建具有所需函数的 C 文件(.c 扩展名)
- 使用 C 编译器创建共享库文件(.so 扩展名)。
- 在 Python 程序中,从共享文件创建 ctypes.CDLL 实例。
- 最后,使用以下格式调用 C 函数
{CDLL_instance}.{function_name}({function_parameters})
.
#include <stdio.h>
int square(int i) {
return i * i;
}
我们有一个简单的 C 函数,它将返回整数的平方。我已将此函数代码保存在名为 my_functions.c 的文件中。
我们可以使用以下命令从 C 源文件创建共享库文件。
$ cc -fPIC -shared -o my_functions.so my_functions.c
>>> from ctypes import *
>>> so_file = "/Users/pankaj/my_functions.so"
>>> my_functions = CDLL(so_file)
>>>
>>> print(type(my_functions))
<class 'ctypes.CDLL'>
>>>
>>> print(my_functions.square(10))
100
>>> print(my_functions.square(8))
64
>>>
如果更改 C 程序文件,则必须重新生成共享库文件。
python 默认实现是用 C 编程编写的,称为 CPython。因此,在 python 程序中使用 C 函数并不罕见。在本教程中,我们学习了如何在 python 程序中轻松调用 C 函数。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)