用swig进行python扩展c语言(范例+错误解决)

来源:互联网 发布:结构方程模型软件 编辑:程序博客网 时间:2024/06/06 16:24

范例来自:http://www.iamlicky.cn/post/221.html
平台是linux,window下编译环节比较麻烦,所以放弃了。

a)首先编写你的c函数,比如如下创建一个test.c文件:

  1. #include    <stdio.h>   
  2. #include    <stdlib.h>   
  3. #include    <time.h>   
  4. void  
  5. func (int n  )  
  6. {  
  7.     printf("This is hello message came from C src!");  
  8.     printf("Let me show u something:/n");  
  9.     int i=0;  
  10.     for(i=1;i<n;i++){  
  11.         int j=1;  
  12.         for(j=1;j<i+1;j++)  
  13.             printf("%d*%d = %2d  ", j, i, i*j);  
  14.         printf("/n");  
  15.     }  
  16.     printf("Did u enjoy it?/nBye,Bye, have fun @.@!/n");  
  17. }     
  18. char * get_time(){  
  19.     time_t ltime;  
  20.     time(&ltime);  
  21.     return ctime(&ltime);  
  22. }  

 b)编写接口文件test.i:

  1. %module test
  2. %{  
  3. /*Put header files here or function declarations like below*/  
  4. extern  void func(int n);  
  5. extern  char * get_time();  
  6. %}  
  7. extern void func(int n);  
  8. extern  char * get_time(); 

c)编译:

  1. #swig -python test.i  (这里给个提示,如果是扩展c++,这里应该这样swig -c++ -python test.i
  2. #gcc -c test.c test_wrap.c -I/usr/include/python2.6  (1》这里可能出现找不到Python.h,或者出现大量的定义神马错误,是缺少python-dev包,即包含各种头文件等的包,请goole:python-dev包 OR在此链接下载(注意版本),http://packages.debian.org/squeeze/python2.6-dev
    1.2》我把dev包的内容覆盖好之后,又提示缺少pyconfig.h,如果没记错的话— —!,要把pyconfig-32.h改为pyconfig.h即可
    2》提示gcc error,可能是你的linux木有gcc,请自行下载,扩展c++请下载多一个g++)
  3. #ld -shared test.o test_wrap.o -o _test.so 
原创粉丝点击