使用ctype在python中调用c

232 阅读1分钟

首先写一个test.c的源码首先写一个test.c的源码

int add(int a, int b)
{
    return a + b;
}

然后编译成.so文件 命令如下

  • gcc -fPIC -c test.c

  • gcc -shared -o test.so test.o

执行完这两个命令之后就出现了test.so文件

现在我们就能在python中调用这个动态链接库了

import ctypes as c

libc = c.cdll.LoadLibrary('/home/yunze/ffb_workspace/ctypes/test.so')

ans = libc.add(10, 2)
print(ans)