Python调用C
关键字:Python ctypes,Python调用dll,Python调用C函数。为了节省软件开发成本,软件开发人员希望能够缩短的软件的开 发时间,希望能够在短时间内开发出稳定的产品。Python 功能强大,简单易用,能够快速开发应用软件。但是由于 Python 自身执行速度的局限性,对性能要求比较高的模块需要使用效率更高的程序语言进行开发,例如 C 语言,系统的其他模块运用 Python 进行快速开发,最后将 C 语言开发的模块与 Python 开发的模块进行整合。在此背景下,基于 Python 语言与 C 语言的各自特点,用 C 语言来扩展现有的 Python 程序,显得很有意义。
本文提供Python以链接库的形式调用C函数的实例。主要用到Python提供的ctypes实现。Python官方教程地址:Ctypes
范例一:Python 调用 C 语言 so
第一步:编写C函数,testlib.c
- 1
- 2
- 3
- 4
- 5
第二步:将C函数编译成链接库
$ gcc -shared -Wl,-soname,testlib -o testlib.so -fPIC testlib.c
第三步:在python中使用C链接库函数,编写python代码test.py如下
- 1
- 2
- 3
第四步:just run it
$ python test.py
hello,www.cricode.com!
范例二:参数类型为字符串(即传指针)
当C函数中,参数类型为字符串时,使用ctypes提供的create_string_buffer来创建缓存区。
第一步:编写C函数testlib1.c
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
第二步:将C函数编译成链接库
$ gcc -shared -Wl,-soname,testlib1 -o testlib1.so -fPIC testlib1.c
第三步:在python中使用C链接库函数,编写python代码test1.py如下:
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
第四步:just run it
$ python test1.py
s0 is: moc.edocirc.www,olleh
s1 is: hello,www.cricode.com
范例三:参数为指针、数组(传指针、数组)
第一步:编写C函数testlib2.c
- 1
- 2
- 3
- 4
第二步:将C函数编译成链接库
$ gcc -shared -Wl,-soname,testlib2 -o testlib2.so -fPIC testlib2.c
第三步:在python中使用C链接库函数
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
第四步:just run it
$ python test2.py
result is: 17
范例四 参数为结构体
第一步:编写C函数testlib3.c
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
第二步:将C函数编译成链接库
$ gcc -shared -Wl,-soname,testlib3 -o testlib3.so -fPIC testlib3.c
第三步:在python中使用C链接库函数,编写python代码test3.py如下:
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
第四步:just run it
$ python test3.py
6 10
- 浅谈 Python 程序和 C 程序的整合
http://www.ibm.com/developerworks/cn/linux/l-cn-pythonandc/ - ctypes https://docs.python.org/2/library/ctypes.html
- http://blog.csdn.net/golden1314521/article/details/44055523