python调用.a静态库_Python 调用 C

本文探讨了如何使用轻量级编译器TCC结合ctypes库,通过编译C源文件为DLL,从而避免直接使用C/C++与Python交互的复杂性。介绍了如何简单地调用生成的DLL,并以test.c中的函数为例进行演示。
摘要由CSDN通过智能技术生成

了解了相关资料

不折腾的方法有(以往文章有):

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.com62ce5c8e17bc8bfb3498f8b8b2a0a70b.png

下面是方法:

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值