了解了相关资料
不折腾的方法有(以往文章有):
pypy,numba,numpy
但都不是 纯正的 C
折腾的:
cffi,Cython,Boost.Python,Cpython 自带模块,SWIG 等
挺折腾的You can write an extension yourself in C or C++ with the Python C-API.
In a word: don't do that except for learning how to do it. It's very difficult to do it correctly. You will have to increment and decrement references by hand and write a lot of code just to expose one function, with very few benefits.
于是想到了 dll,编译生成 dll,再去调用。
比较常用的轻量编译器是 tcc,可以搜到 python-bindSasView/tinyccgithub.com
下面是方法:
test.c
int add(int a, int b)
{
return a + b;
}
main.py
from tinycc import compile
from ctypes import cdll
dll_path = compile("test.c") # dll_path 是生成的 dll 的路径
my = cdll.LoadLibrary(r"your path to test.dll")
print(my.add(1, 2))
运行 main.py 就完成了编译 dll + 调用
test.c
#include
int add(int a, int b)
{
return a + b;
}
int sub(int a, int b)
{
return a - b;
}
int len(const char *c)
{
return strlen(c);
}
main.py
from tinycc import compile
from ctypes import cdll
dll_path = compile("test.c")
my = cdll.LoadLibrary(r"path to test.dll")
print(my.add(2 ** 31 + 3, 2), my.sub(3, 6), my.len(b"tssss"))
-2147483643 -3 5