Python 使用C代码——swig

来源:互联网 发布:黑魂3防火女化妆数据 编辑:程序博客网 时间:2024/04/29 21:53

Ref : http://www.swig.org/translations/chinese/tutorial.html

 

假设你有一些c你想再加Python.。举例来说有这么一个文件example.c
 /* File : example.c */
 #include <time.h>
 double My_variable = 3.0;
 int fact(int n) {
     if (n <= 1) return 1;
     else return n*fact(n-1);
 }
 
 int my_mod(int x, int y) {
     return (x%y);
 }

 char *get_time()
 {
     time_t ltime;
     time(&ltime);
     return ctime(&ltime);
 }

 接口文件
现在,为了增加这些文件到你喜欢的语言中,你需要写一个接口文件(interface file)投入到swig中。这些C functions的接口文件可能如下所示:

     /* example.i */
     %module example
     %{
     /* Put header files here or function declarations like below */
     extern double My_variable;
     extern int fact(int n);
     extern int my_mod(int x, int y);
     extern char *get_time();
     %}
    
     extern double My_variable;
     extern int fact(int n);
     extern int my_mod(int x, int y);
     extern char *get_time();
    
      建立Python模块
转换编码C成Python模块很简单,只需要按如下做即可(请见其他操作系统的SWIG 共享库帮助手册):

     unix % swig -python example.i
     unix % gcc -c -fPIC -m32 example.c example_wrap.c /
            -I/usr/(local/include/python2.1)include/python2.4
    unix % (ld)gcc -shared -m32 example.o example_wrap.o -o _example.so

关于以上红蓝绿颜色字解释:
1. -fPIC 我的系统中不加该编译选项时,下面编译-share的库文件会出错。
2. -m32选项,gcc版本高于4.1时,编译出的代码默认是64位的,在执行下面 >>>import example时会出现错误:
ImportError: ./_example.so: wrong ELF class: ELFCLASS64。而Python这时默认使用的是32位,
这里加-m32选项使gcc编译出32位库代码。[根据自己的系统决定是否添加该选项]
3. 绿色文字括号中的是原文,括号外是我的系统应该使用的路径和命令。[根据自己的系统决定具体路径和命令

我们现在可以使用如下Python模块 :

     >>> import example
     >>> example.fact(5)
     120
     >>> example.my_mod(7,3)
     1
     >>> example.get_time()
     'Sun Feb 11 23:01:07 1996'
     >>>

原创粉丝点击