您的位置:首页 > 编程语言 > C语言/C++

使用swig进行C/C++对Python的扩展

2013-05-06 21:22 676 查看
1、swig简介:

SWIG是个帮助使用C或者C++编写的软件能与其它各种高级编程语言进行嵌入联接的开发工具。SWIG能应用于各种不同类型的语言包括常用脚本编译语言例如Perl, PHP, Python, Tcl, Ruby and PHP。支持语言列表中也包括非脚本编译语言,例如C#, Common Lisp (CLISP, Allegro CL, CFFI, UFFI), Java, Modula-3, OCAML以及R,甚至是编译器或者汇编的计划应用(Guile, MzScheme, Chicken)。SWIG普遍应用于创建高级语言解析或汇编程序环境,用户接口,作为一种用来测试C/C++或进行原型设计的工具。SWIG还能够导出XML或Lisp
s-expressions格式的解析树。SWIG可以被自由使用,发布,修改用于商业或非商业中。

2、使用swig进行C对Python的扩展

1)、编写mytest.c和mytest.h文件

mytest.h

#ifndef __MYTEST_H__
#define __MYTEST_H__

void hello();
int add(int a,int b);

#endif


mytest.c

#include<stdio.h>
#include"mytest.h"

void hello(){
printf("This is a test for swig and Python \n");
}

int add(int a,int b){
return a+b;
}


2、编写mytest.i

mytest.i

%module mytest

%{
#include <stdio.h>
#include "mytest.h"
%}
extern void hello();
extern int add(int a,int b);


第一部分是%module mytest,%module是SWIG脚本的一个命令,它表示生成的包装器将在一个模块内的名称。

第二部分是%{... %},这一部分的内容会原封不动的插入到 xxxx_wrap.c或 xxxx_wrap.cxx文件中。

第三部分就是剩下的部分了。这部分就是C语言或者C++语言的接口声明了。和C/C++的语法是一样的。

其实用

%include "mytest.h"


来代替

extern void hello();
extern int add(int a,int b);


也是一样的。

3)、执行 swig -python mytest.i ,生成 mytest.py mytest_wrap.c

4)、执行gcc -shared -fpic -o _mytest.so -I/usr/include/python2.7 -I/usr/lib/python2.7/config mytest.c mytest_wrap.c,生成_mytest.so,注意一定是生成_mytest.so,如果写成mytest.so,在后面调用时会有错误:

Traceback (most recent call last):
File "mypy.py", line 1, in <module>
import mytest
ImportError: dynamic module does not define init function (initmytest)


5)、编写mypy.py

import mytest

mytest.hello()
print mytest.add(10,20)


6)、执行 python mypy.py,可以看到打印结果。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: