ctypes是傳統的加速方式,先用c++或者c將代碼編譯為動態庫,由ctypes來進行調用。
c++樣例代碼 count.cc
#include <iostream>
#include<iomanip>
#include<time.h>
using namespace std;
extern "C" int count(int n){
int ans = 0;
for( int i = 0; i <= n; i+=1 ){
ans = ans + 1;
}
return ans;
}
運行g++ -o count.so -shared -fPIC count.cc -O2 生成動態庫
python3調用測試代碼
from ctypes import *
ctype_handel = cdll.LoadLibrary("./count.so")
print(ctype_handel.count(c_int(9999)))