C语言部分:

先写一个a.c文件

  1. #include <stdio.h>
  2. void show() {
  3. printf("this is a test\n");
  4. }
  5. int add(int a, int b) {
  6. return a + b;
  7. }

输入命令

  1. gcc a.c -fPIC -shared -o a.so

在当前目录下会产生一个a.so文件
-fPIC是position independent code(位置无关代码)的意思
-shared是产生一个可以与其他对象连接来形成一个可执行文件的共享对象的一个参数

Python部分:

python中调用.so库

  1. from ctypes import cdll
  2. cur = cdll.LoadLibrary('./a.so')
  3. cur.show()
  4. print cur.add(1, 2)

结果如下:

hello, world!
3