1
我有C++類,需要在python代碼中使用它。爲此,使用SWIG生成一個包裝類。按照文件中配置的example.iSwig Python - 沒有適當的默認構造函數可用
/* File: example.i */
%module example
%{
#define SWIG_FILE_WITH_INIT
#include "item.h"
#include "GradedComplex.h"
#include "GradedDouble.h"
%}
%include "item.h"
%include "GradedComplex.h"
%include "GradedDouble.h"
並試圖用建立它下面的命令
c:>swig -c++ -python example.i
c:>python setup.py build_ext --inplace
的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_); }
Item<T> &operator+=(Item<T> &rhs)
{
val_ += rhs();
return *this;
}
Item<T> &operator-=(Item<T> &rhs)
{
val_ -= rhs();
return *this;
}
Item<T> &operator*=(Item<T> &rhs)
{
val_ *= rhs();
return *this;
}
};
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
不過還是我收到以下錯誤
example_wrap.cxx(3275) : error C2512: 'Item<std::complex<double>>' : no appropriate default constructor available
c:\documents and settings\swig\Item.h(38) : warning C45
21: 'Item<T>' : multiple copy constructors specified
with
[
T=double
]
example_wrap.cxx(3425) : see reference to class template instantiation '
Item<T>' being compiled
with
[
T=double
]
error: command '"C:\Program Files\Microsoft Visual Studio 9.0\VC\BIN\cl.exe"' fa
iled with exit status 2
請給我一些建議。
嘗試範圍縮小到一個小例子,你可以在它的全部張貼。 –