简体   繁体   English

如何创建SWIG接口文件?

[英]How to create SWIG interface file?

I am new to SWIG 我是SWIG的新手

And less time to do things. 而且做事的时间更少。 I am trying to bind c++ classes to python. 我试图将c ++类绑定到python。 I have set up SWIG in windows and tried running it. 我在Windows中设置了SWIG并尝试运行它。 It was successful 成功了

My example.i file is like 我的example.i文件就像

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

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

But it seems it has to include or declare the header files class, constructor, templates etc... 但它似乎必须包含或声明头文件类,构造函数,模板等...

Can anyone suggest how to create a SWIG interface file. 任何人都可以建议如何创建SWIG接口文件。

Follwing are the header file (Item.h) that i need to create interface file. 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

Here's an interface file for your example. 这是您的示例的接口文件。 SWIG has built-in support for std::string and std::complex. SWIG内置了对std :: string和std :: complex的支持。 You must declare the concrete classes of the templates you want to use via %template: 您必须通过%template声明要使用的模板的具体类:

%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> >;

Use it like: 使用它像:

>>> 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM