---
title: "用C语音编写python的扩展模块，也就是python调c库"
author: "8366"
date: "2012-07-09T11:17:20Z"
tags: []
categories: ["编程语言"]
slug: "c-python-python-c"
draft: false
lastmod: "2012-07-09T11:19:13Z"
id: 1575189
url: "https://8366.iteye.com/blog/1575189"
---

参考资料：

 

1.用C语言扩展Python的功能:

# http://www.ibm.com/developerworks/cn/linux/l-pythc/

2.用C语言编写Python扩展模块:

http://hi.baidu.com/jinmu190/blog/item/c5475846eee39c056a63e5f1.html

[3.怎样编写python脚本的C扩展模块](http://blog.csdn.net/dengxu11/article/details/7393395)

http://blog.csdn.net/dengxu11/article/details/7393395

 

4.[使用C语言扩展Python](http://www.cnblogs.com/phinecos/archive/2010/05/23/1742344.html)

http://www.cnblogs.com/phinecos/archive/2010/05/23/1742344.html

 

 

我们知道python是一种很好的胶水语言，现在有个问题，如何让python 调用到c程序，  
假如c程序已经是成熟的code.

方式有3种：  
1.直接调用动态库  
2.通过SWIG接口  
前面2中方式参考： http://www.2cto.com/kf/201009/74906.html  
3.为调用者python 写一个c的扩展包

需求：有一个POC的项目，需要在openstack的 源码里面加入我们自己的控制逻辑.openstack是  
python 写的，我们自己的控制逻辑是个成熟的code,(大量的so), 我们需要在python code中调用  
c code. 我们采用 方式3 为python写一个 扩展包，然后在python中调用 c code

例子：为say.c 编写一个 符合python 标准的扩展包

 a. say.h 已经存在,里面有2个函数定义 sayhello, saybye  
 b. say.c 已经存在,里面实现了 say.h 中定义的方法  
 c. sayModule.c 是为 python 调用者写的 一个扩展包，最终会使用 distutils 编译成say.so  
 d. setUp.py，将c code 打包成 so ：  
   
 \[root@egovmo03 C]# python setup.py install  
running install  
running build  
running build\_ext  
building 'say' extension  
creating build  
creating build/temp.linux-x86\_64-2.4  
gcc -pthread -fno-strict-aliasing -DNDEBUG -O2 -g -pipe -Wall -Wp,-D\_FORTIFY\_SOURCE=2 -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m64 -mtune=generic -D\_GNU\_SOURCE -fPIC -fPIC -I/usr/include/python2.4 -c sayModule.c -o build/temp.linux-x86\_64-2.4/sayModule.o  
gcc -pthread -fno-strict-aliasing -DNDEBUG -O2 -g -pipe -Wall -Wp,-D\_FORTIFY\_SOURCE=2 -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m64 -mtune=generic -D\_GNU\_SOURCE -fPIC -fPIC -I/usr/include/python2.4 -c say.c -o build/temp.linux-x86\_64-2.4/say.o  
creating build/lib.linux-x86\_64-2.4  
gcc -pthread -shared build/temp.linux-x86\_64-2.4/sayModule.o build/temp.linux-x86\_64-2.4/say.o -o build/lib.linux-x86\_64-2.4/say.so  
running install\_lib  
copying build/lib.linux-x86\_64-2.4/say.so -&gt; /usr/lib64/python2.4/site-packages  
\[root@egovmo03 C]#

测试：

\[root@egovmo03 C]# python  
Python 2.4.3 (#1, Jun 11 2009, 14:09:37)  
\[GCC 4.1.2 20080704 (Red Hat 4.1.2-44)] on linux2  
Type "help", "copyright", "credits" or "license" for more information.  
&gt;&gt;&gt; import say  
&gt;&gt;&gt; dir(say)  
\['\_\_doc\_\_', '\_\_file\_\_', '\_\_name\_\_', 'bye', 'error', 'hello', 'say']   -&gt;&gt;&gt; say 模块多了 hello 和 bye方法  
&gt;&gt;&gt; aa='xpxp'  
&gt;&gt;&gt; say.hello(aa);  
hello, xpxp  
&gt;&gt;&gt; say.bye(aa);  
bye, xpxp  
&gt;&gt;&gt;