在Python中引入C文件通常有以下几种方法:
1. 使用`ctypes`模块:
编写C代码并保存为`.c`文件。
使用`gcc`将C代码编译为共享库(如`.so`文件)。
在Python代码中使用`ctypes.cdll.LoadLibrary`加载共享库。
使用`ctypes.find_function`或`ctypes.find_variable`获取库中的函数或变量。
2. 使用`cffi`模块:
编写C代码并保存为`.c`文件。
使用`cffi`生成C扩展模块。
在Python代码中导入生成的C扩展模块。
下面是一个使用`ctypes`模块引入C文件的示例:
C代码 (example.c):
include
__attribute__((visibility("default")))
int add_integers(int a, int b) {
return a + b;
}
__attribute__((visibility("default")))
float add_floats(float a, float b) {
return a + b;
}
Python代码 (pydemo.py):
import ctypes
加载共享库
mylib = ctypes.CDLL('./libtest.so')
获取函数
add_integers = mylib.add_integers
add_floats = mylib.add_floats
调用函数
result_int = add_integers(3, 4)
result_float = add_floats(3.0, 4.0)
print(f"3 + 4 = {result_int}")
print(f"3.0 + 4.0 = {result_float}")
确保在编译C代码时使用了正确的编译选项,例如`-fPIC -shared`,以生成可以在Python中加载的共享库。