zoukankan      html  css  js  c++  java
  • 用C语音编写python的扩展模块,也就是python调c库

    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

    4.使用C语言扩展Python

    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 -> /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.
    >>> import say
    >>> dir(say)
    ['__doc__', '__file__', '__name__', 'bye', 'error', 'hello', 'say']   ->>> say 模块多了 hello 和 bye方法
    >>> aa='xpxp'
    >>> say.hello(aa);
    hello, xpxp
    >>> say.bye(aa);
    bye, xpxp
    >>>

  • 相关阅读:
    Linux 上网络监控工具 ntopng 的安装
    Linux 运维工程师的十个基本技能点
    HashMap、Hashtable、ConcurrentHashMap的区别
    Spark会产生shuffle的算子
    Scala基础:闭包、柯里化、隐式转换和隐式参数
    Scala基础:模式匹配和样例类
    Scala基础:面向对象之trait
    Scala基础:面向对象之对象和继承
    Scala基础:类和构造器
    Scala基础:数组(Array)、映射(Map)、元组(Tuple)、集合(List)
  • 原文地址:https://www.cnblogs.com/L-H-R-X-hehe/p/3817569.html
Copyright © 2011-2022 走看看