Chinaunix首页 | 论坛 | 博客
  • 博客访问: 303439
  • 博文数量: 21
  • 博客积分: 250
  • 博客等级: 二等列兵
  • 技术积分: 484
  • 用 户 组: 普通用户
  • 注册时间: 2010-10-06 23:10
个人简介

程序猿

文章分类

全部博文(21)

文章存档

2016年(17)

2014年(3)

2013年(1)

分类: Python/Ruby

2016-07-16 15:05:47

Python作为一门脚本语言,让程序员的开发效率变得非常高。但相对来说,程序执行的效率就比不上C、C++等编译型语言了。对此,可以做一个“妥协”,即把效率影响较大的函数用C来实现,Python代码中调用这些函数,实现开发效率和运行效率的平衡。

代码编写

我们通过一个例子来了解python和C混合编程的步骤。例子中用C语言实现两个整数相加,在Python中调用这个函数并输出结果。
首先,用C实现函数add,并编译成动态库liboper.so:
  1. # cat oper.c
  2. int add(int a, int b)
  3. {
  4.         return a + b;
  5. }
  1. # gcc oper.c -fPIC -shared -o liboper.so

在Python中调用C的函数,首先需要导入其所在的动态函数库,可以使用Python内建模块ctypes。
代码如下:
  1. # cat main.py
  2. import ctypes
  3. oper = ctypes.CDLL("./liboper.so")
  4. print oper.add(3, 4)

运行:
  1. # python main.py
  2. 7


调试

我们知道,调试Python代码可以使用pdb。但是要调试被Python调用的C代码,就需要用到C语言的调试工具:gdb

为了看到调试信息,需要在编译动态库的时候增加-g选项:
  1. # gcc oper.c -g -fPIC -shared -o liboper.so

然后运行gdb python,并打断点到add函数,具体过程如下:
  1. # gdb python
  2. GNU gdb (Ubuntu 7.7.1-0ubuntu5~14.04.2) 7.7.1
  3. Copyright (C) 2014 Free Software Foundation, Inc.
  4. License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
  5. This is free software: you are free to change and redistribute it.
  6. There is NO WARRANTY, to the extent permitted by law. Type "show copying"
  7. and "show warranty" for details.
  8. This GDB was configured as "x86_64-linux-gnu".
  9. Type "show configuration" for configuration details.
  10. For bug reporting instructions, please see:
  11. <http://www.gnu.org/software/gdb/bugs/>.
  12. Find the GDB manual and other documentation resources online at:
  13. <http://www.gnu.org/software/gdb/documentation/>.
  14. For help, type "help".
  15. Type "apropos word" to search for commands related to "word"...
  16. Reading symbols from python...Reading symbols from /usr/lib/debug//usr/bin/python2.7...done.
  17. done.
  18. (gdb) b add
  19. Function "add" not defined.
  20. Make breakpoint pending on future shared library load? (y or [n]) y
  21. Breakpoint 1 (add) pending.
  22. (gdb) run main.py
  23. Starting program: /usr/bin/python main.py
  24. [Thread debugging using libthread_db enabled]
  25. Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1".

  26. Breakpoint 1, add (a=3, b=4) at oper.c:3
  27. 3 return a + b;
  28. (gdb) list
  29. 1 int add(int a, int b)
  30. 2 {
  31. 3 return a + b;
  32. 4 }
  33. 5
  34. (gdb)
可以看到,程序在add函数上断了下来。但是,我们无法看到目前Python的代码运行到哪里了。要解决这个问题,需要安装Python的调试扩展工具。Ubuntu下安装方法(针对Python2)如下:
  1. sudo apt-get install python2.7-dbg

重新运行上面的指令,断下来后就可以使用py-前缀的命令看到Python代码运行到的位置了。
  1. (gdb) py-bt
  2. #9 Frame 0x7ffff7f8f050, for file main.py, line 3, in <module> ()
  3.     print so.add(3, 4)
  4. (gdb) py-list
  5.    1 import ctypes
  6.    2 so = ctypes.CDLL("./liboper.so")
  7.   >3 print so.add(3, 4)
  8.    4





阅读(5076) | 评论(0) | 转发(0) |
0

上一篇:golang 测试

下一篇:没有了

给主人留下些什么吧!~~