如果我问你如何使用 Python 去执行 C 语言的代码,我猜你第一反应是通过 os
包在命令行执行。
os.system()
os.popen()
但是这样执行是通过将 C 语言编译成二进制文件,然后在命令行执行,这样的执行既不灵活也不 Pythonic
。
那么有没有一种类似使用 Python import
的方法,直接通过 Python 去执行 C 代码呢?答案是有的!
我们可以将 C 语言代码编译成动态库,然后使用 ctypes
包将 C 语言的动态库 import
进来,然后像使用 Python 对象一样的使用 C 语言动态库。
我们先写一个 C 语言的函数:
hello.c
#include <stdio.h>
int add(int num1, int num2)
{
return num1 + num2;
}
然后我们在命令行将 hello.c
编译成 hello.so
。
MacBook:Downloads zhangyi$ gcc -o hello.so -shared -fPIC hello.c
MacBook:Downloads zhangyi$ ls hello.
hello.c hello.so
最后我们在 Python 代码里调用 C 语言函数。
In [1]: import ctypes
In [2]: lib = ctypes.cdll.LoadLibrary('hello.so')
In [3]: lib.add(1, 2)
Out[3]: 3
In [4]: lib.add(2, 2)
Out[4]: 4