从Python调用C函数
时间:2020-02-23 14:42:12 来源:igfitidea点击:
我们可以使用ctypes模块从Python程序调用C函数。
从Python调用C函数
它涉及以下步骤:
使用所需功能创建C文件(扩展名为.c)
使用C编译器创建共享库文件(扩展名为.so)。
在Python程序中,从共享文件创建一个ctypes.CDLL实例。
最后,使用格式{CDLL_instance}。
{function_name}({function_parameters})调用C函数。
步骤1:创建具有某些功能的C文件
#include <stdio.h> int square(int i) { return i * i; }
我们有一个简单的C函数,该函数将返回整数的平方。
我已将此功能代码保存在名为my_functions.c的文件中。
步骤2:创建共享库文件
我们可以使用以下命令从C源文件创建共享库文件。
$cc -fPIC -shared -o my_functions.so my_functions.c
C文件和共享库文件
步骤3:从Python程序调用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程序文件,则必须重新生成共享库文件。