Python作为一门脚本语言,让程序员的开发效率变得非常高。但相对来说,程序执行的效率就比不上C、C++等编译型语言了。对此,可以做一个“妥协”,即把效率影响较大的函数用C来实现,Python代码中调用这些函数,实现开发效率和运行效率的平衡。
代码编写
我们通过一个例子来了解python和C混合编程的步骤。例子中用C语言实现两个整数相加,在Python中调用这个函数并输出结果。
首先,用C实现函数add,并编译成动态库liboper.so:
-
# cat oper.c
-
int add(int a, int b)
-
{
-
return a + b;
-
}
-
# gcc oper.c -fPIC -shared -o liboper.so
在Python中调用C的函数,首先需要导入其所在的动态函数库,可以使用Python内建模块ctypes。
代码如下:
-
# cat main.py
-
import ctypes
-
oper = ctypes.CDLL("./liboper.so")
-
print oper.add(3, 4)
运行:
调试
我们知道,调试Python代码可以使用pdb。但是要调试被Python调用的C代码,就需要用到C语言的调试工具:gdb
为了看到调试信息,需要在编译动态库的时候增加-g选项:
-
# gcc oper.c -g -fPIC -shared -o liboper.so
然后运行gdb python,并打断点到add函数,具体过程如下:
-
# gdb python
-
GNU gdb (Ubuntu 7.7.1-0ubuntu5~14.04.2) 7.7.1
-
Copyright (C) 2014 Free Software Foundation, Inc.
-
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
-
This is free software: you are free to change and redistribute it.
-
There is NO WARRANTY, to the extent permitted by law. Type "show copying"
-
and "show warranty" for details.
-
This GDB was configured as "x86_64-linux-gnu".
-
Type "show configuration" for configuration details.
-
For bug reporting instructions, please see:
-
<http://www.gnu.org/software/gdb/bugs/>.
-
Find the GDB manual and other documentation resources online at:
-
<http://www.gnu.org/software/gdb/documentation/>.
-
For help, type "help".
-
Type "apropos word" to search for commands related to "word"...
-
Reading symbols from python...Reading symbols from /usr/lib/debug//usr/bin/python2.7...done.
-
done.
-
(gdb) b add
-
Function "add" not defined.
-
Make breakpoint pending on future shared library load? (y or [n]) y
-
Breakpoint 1 (add) pending.
-
(gdb) run main.py
-
Starting program: /usr/bin/python main.py
-
[Thread debugging using libthread_db enabled]
-
Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1".
-
-
Breakpoint 1, add (a=3, b=4) at oper.c:3
-
3 return a + b;
-
(gdb) list
-
1 int add(int a, int b)
-
2 {
-
3 return a + b;
-
4 }
-
5
-
(gdb)
可以看到,程序在add函数上断了下来。但是,我们无法看到目前Python的代码运行到哪里了。要解决这个问题,需要安装Python的调试扩展工具。Ubuntu下安装方法(针对Python2)如下:
-
sudo apt-get install python2.7-dbg
重新运行上面的指令,断下来后就可以使用py-前缀的命令看到Python代码运行到的位置了。
-
(gdb) py-bt
-
#9 Frame 0x7ffff7f8f050, for file main.py, line 3, in <module> ()
-
print so.add(3, 4)
-
(gdb) py-list
-
1 import ctypes
-
2 so = ctypes.CDLL("./liboper.so")
-
>3 print so.add(3, 4)
-
4
阅读(5259) | 评论(0) | 转发(0) |