关于gcc以及python的版本配置建议大家去看我之前的一篇文章,里面比较详细地点明了关于32位和64的一些坑。
接下来将简单介绍python如何调用C和C++。包括调用整型,数组等情况。
python 调用C
C函数返回整型int
c代码 test.c
#include <stdio.h>
#include <stdlib.h>
int func(int a, int b)
{
int ans = a + b;
printf("You input %d and %d\n", a, b);
printf("The result is %d\n", ans);
return ans;
}
编译成so包
gcc -o testpycll_64.so -shared -fPIC test.c
其中参数‘-fPIC’:当产生共享库的时候,应该创建位置无关的代码,这会让共享库使用任意的地址而不是固定的地址,要实现这个功能,需要使用-fPIC参数。
python代码
import ctypes
import platform
ll = ctypes.cdll.LoadLibrary
lib = ll("./testpycll_64.so")
lib.func(1,3)
# platform.architecture()
运行之后的结果:
这里有一个问题,我是在jupyter notebook下的,只显示了C函数的返回值,对于过程打印语句并没有输出。但在命令行下是可以输出的,如下所示:
mypy.py 是python文件名。
C函数返回整型数组 int[]
C代码:
#include <stdio.h>
#include <stdlib.h>
int* func(int a, int b)
{
int* res = (int *)malloc(3*sizeof(int));
int ans = a + b;
printf("You input %d and %d\n", a, b);
printf("The result is %d\n", ans);
res[0] = a;
res[1] = b;
res[2] = ans;
return res;
//return ans;
}
python 代码:需要用到numpy包
(这里原先一直返回失败,也是试了非常多的方法才解决)
import ctypes
import platform
from numpy.ctypeslib import ndpointer
ll = ctypes.cdll.LoadLibrary
lib = ll("./testpycll_64.so")