先來一個網(wǎng)上隨便都能找得到的例子吧:先來一個test.c
#include "test.h"
void test(){
printf("hello so\n");
}
float add(float a, float b){
return a+b;
}
在來一個test.h:
#include "stdio.h"
void test();
float add(float, float);
然后將其編譯成.so文件:
gcc -fPIC -shared test.c -o libtest.so
最后在python文件里面調(diào)用:
#!/usr/bin/env python
print "start call so file\n"
from ctypes import *
test = cdll.LoadLibrary("./libtest.so")
test.test()
add =test.add
add.argtypes =[c_float, c_float]
add.restype =c_float
print add(1.3, 13.4)
然后在終端運行:
root@localhost:~/python/call_so# python test.py
start call so file
hello so
14.6999998093
嗯糖权,python2的這個數(shù)字精度的bug也是醉了
當然了,ctypes不是這樣簡單的模塊狂男,否則也不會放到標準庫里面去
(未完待續(xù)坛芽。赘风。蒋腮。)