swig不做介绍,python更不做介绍,自己去网上搜吧
linxu下安装swig需要的源码包在这里下
笔者下到的:
wget "" -O pcre-8.12.zip
wget -O swigwin-2.0.4.zip
安装步骤
1.unzip这哥俩
2.先装pcre,进入pcre-8.12目录 ./configure ./make ./make install
3.再装swig,进入swigwin-2.0.4目录 ./configure ./make ./make install
4.小试一下,进入 swigwin-2.0.4/Examples/python/simple,make生成example.py _example.so
这里做必要的解释:
simple目录下有Makefile example.c【C源码】 example.i【Interface定义】
------------------------------------------------源码例子-----------------------------------------------
-------------------example.c-------------------
/* File : example.c */
/* A global variable */
double Foo = 3.0;/* Compute the greatest common divisor of positive integers */
int gcd(int x, int y) { int g; g = y; while (x > 0) { g = x; x = y % x; y = g; } return g;}-------------------example.i-------------------
/* File : example.i */
%module example%inline %{
extern int gcd(int x, int y);extern double Foo;%}5.使用范例,make之,生成_example.so:
>>> import example>>> example.gcd(13,10)1>>> example.gcd(3,12)3-----------------------------------------------常用方法[轻松定义.i文件]--------------------------------------
------example.h------
#include <iostream>
using namespace std;
enum DAY { SUN, MON, TUE, WEN, THR, FRI, STU};
class Example{
public:
void say_hello();
DAY get_cur_day();
};
------example.cpp------
#include "example.h"
#include "stdio.h"
void Example::say_hello(){ cout<<"hello"<<endl;}
DAY Example::get_cur_day(){return SUN;}
------example.i------
%module example
%{
#include "example.h"
%}
%include "example.h"
------setup.py------
#! /data6/peterguo/sea/tool/python/bin/python
from distutils.core import setup, Extension
example_module = Extension('_example', sources=['example.cpp', 'example_wrap.cxx',],)
setup(name="example", version="0.1", author="peterguo@vip.qq.com", ext_modules = [example_module],py_modules = ["example"],)
生成python代码
swig -c\+\+ -python example.i ---->> example.py example_wrap.cxx
调用gcc进行编译
python ./setup.py build_ext --inplace ---->> _example.so ./build子目录
有了example.py和_example.so就可以使用这个类了。
参考: www.swig.org/papers/PyTutorial98/PyTutorial98.pdf