python调用C语言程序(通过自己构建的动态链接库)
这里先演示在windows环境下调用自己编译的dll库,这里我用ctypes实现
ctypts是python自带的库,无需额外安装
先写一个有被调用函数的C源文件test.c
#include <stdio.h>
int foo(int a, int b){
printf("u input %d and %d \n",a,b);
return a+b;
}
注意这里的函数名foo
,一会用到
将其用gcc编译成.dll文件和.so文件,默认生成在当前目录。这里只演示生成dll文件的
gcc -o test.dll -shared -fPIC test.c
现在再写一个调用这个dll库的python代码test.py
import ctypes
c_lib=ctypes.CDLL('./test.dll')
c_lib.foo.argtypes=[ctypes.c_int,ctypes.c_int]
c_lib.foo.restype=ctypes.c_int
result=c_lib.foo(2,3)
print(result)
可以自己体会一下ctypes的使用方法
执行这个python程序
PS D:\demo_for_newKL> & C:/Users/d0ubleU0x00/AppData/Local/Programs/Python/Python312/python.exe d:/demo_for_newKL/test.py
u input 2 and 3
5
可以发现执行了C语言函数foo的语句
原文地址:https://blog.csdn.net/m0_52682586/article/details/142989381
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!