python调用.a静态库_Python 调用 C
了解了相關資料
不折騰的方法有(以往文章有):
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/tinycc?github.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
總結
以上是生活随笔為你收集整理的python调用.a静态库_Python 调用 C的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 在java中的交换方法有哪些_java中
- 下一篇: java 方法重载的作业_java第六章