2012-11-13 36 views
1

我是SWIG新手如何創建SWIG接口文件?

做事情的時間少了。 我想將C++類綁定到python。 我已經在Windows中設置了SWIG並嘗試運行它。這是成功的

我example.i文件就像

/* File: example.i */ 
%module example 

%{ 
#define SWIG_FILE_WITH_INIT 
#include "Item.h" 
}% 
#include "Item.h" 

但現在看來,這必須包括或聲明的頭文件類的構造函數,模板等...

任何人都可以建議如何創建一個SWIG接口文件。

Follwing是我需要創建接口文件的頭文件(Item.h)。

#ifndef __ITEM_H__ 
#define __ITEM_H__ 

#include <complex> 
#include <functional> 
#include <string> 

template<typename T> 
class Item 
{ 
    std::string name_; 
    T val_; 

public: 
    Item(std::string name, T val) : name_(name), val_(val) {} 
    Item(Item<T> &rhs) : name_(rhs.name_), val_(rhs.val_) {} 
    Item(const Item<T> &rhs) : name_(rhs.name_), val_(rhs.val_) {} 
    ~Item() {} 

    std::string name() const { return name_; } 
    T operator()() const { return val_; } 
    double norm() const { return sqrt(val_ * val_); } 
}; 

template<> 
class Item<std::complex<double> > 
{ 
    std::string name_; 
    std::complex<double> val_; 

public: 
    Item(std::string name, std::complex<double> val) : name_(name), val_(val) {} 
    Item(Item<std::complex<double> > &rhs) : name_(rhs.name_), val_(rhs.val_) {} 
    Item(const Item<std::complex<double> > &rhs) : name_(rhs.name_), val_(rhs.val_) {} 
    ~Item() {} 

    std::string name() const { return name_; } 
    std::complex<double> operator()() const { return val_; } 
    double norm() const { return sqrt(val_.real() * val_.real() + val_.imag() * val_.imag()); } 
}; 

template<typename T> 
struct ItemComparator : public std::binary_function<Item<T>, Item<T>, bool> 
{ 
    inline bool operator()(Item<T> lhs, Item<T> rhs) 
    { 
    return lhs.norm() < rhs.norm(); 
    } 
}; 

#endif 
+0

你怎麼能指望一個C++模板類導出到Python的? AFAIK只能導出專業化。此外,不要使用以雙下劃線開頭的名稱http://stackoverflow.com/questions/228783/what-are-the-rules-about-using-an-underscore-in-a-c-identifier。 –

+0

您也可以考慮[boost.python](http://www.boost.org/doc/libs/release/libs/python/)作爲SWIG的替代方案。我發現編寫高質量的包裝比使用SWIG更容易。 –

回答

4

這是您的示例的接口文件。 SWIG內置了對std :: string和std :: complex的支持。你必須通過模板%申報要使用模板的具體類:

%module Item 

%{ 
#include "Item.h" 
%} 

%include <std_string.i> 
%include <std_complex.i> 
%include "Item.h" 
%template(Int) Item<int>; 
%template(Complex) Item<std::complex<double> >; 

這樣使用它:

>>> import Item 
>>> a=Item.Int('Int1',5) 
>>> b=Item.Complex('Cplx1',2+3j) 
>>> a.name() 
'Int1' 
>>> b.name() 
'Cplx1' 
>>> a.norm() 
5.0 
>>> b.norm() 
3.605551275463989 
+0

感謝您寶貴的時間... –

+0

我正在使用Swig for PHP,我需要在PHP中調用C++函數。我不知道如何創建接口文件,語法是什麼,%inline或%{%}是什麼意思?有人可以請澄清我嗎? – Sanket