> 文档中心 > Python编程-python与其它语言的互相调用(三):python调用C语言代码

Python编程-python与其它语言的互相调用(三):python调用C语言代码

python,最被广泛使用的脚本利器。-----箴言-----

 

1. 内容简介:

本节介绍在python中调用c语言的几种方式:

python调用c的可执行程序

python调用c的lib库;

 

2. python调用c的可执行程序

实例如下:

c语言:打印hello

#include int main() {    printf("hello c main!\n");    return 0;}

编译运行:

aaaaa:py_c user1$ gcc hello.caaaaa:py_c user1$ lsa.out     hello.caaaaa:py_c user1$ ./a.out hello c main!

python中调用a.out:

#!/usr/bin/python# -*- coding: UTF-8 -*-import osimport sys#mainif __name__ == '__main__':c = 'a.out'os.system(c)

运行结果:

aaaaa:py_c user1$ python3 call_c.py hello c main!

3. python中调用C语言编译的so库:

在c语言中,使用dlopen进行so库的加载,那么,在python中,如何加载以及调用C库中的函数呢?

在python中,可以使用ctypes中的CDLL来加载so库。

举例如下:

so代码:hello_so.c

#include int print_hello() {    printf("hello c lib!\n");    return 0;}//编译:aaaaa:py_c user1$ gcc -fPIC -shared hello_so.c -o libhello.soaaaaa:py_c user1$ lsa.outcall_c.py   hello.c     hello_so.c  libhello.so
libhello.so就是编译成功的so库。在python中调用:
#!/usr/bin/python# -*- coding: UTF-8 -*-import osimport sysfrom ctypes import *#mainif __name__ == '__main__':c = 'a.out'os.system(c)#call c libc_lib = CDLL('./libhello.so')#调用c中定义的函数c_lib.print_hello();
运行结果:

aaaaa:py_c user1$ python3 call_c.py 

hello c main!

hello c lib!

 

调用成功。


欢迎点赞,评论,转发 :)