C语言部分:
先写一个a.c文件
#include <stdio.h>void show() {printf("this is a test\n");}int add(int a, int b) {return a + b;}
输入命令
gcc a.c -fPIC -shared -o a.so
在当前目录下会产生一个a.so文件
-fPIC是position independent code(位置无关代码)的意思
-shared是产生一个可以与其他对象连接来形成一个可执行文件的共享对象的一个参数
Python部分:
python中调用.so库
from ctypes import cdllcur = cdll.LoadLibrary('./a.so')cur.show()print cur.add(1, 2)
结果如下:
hello, world!
3
