2012-11-15 38 views
1

我是SWIG的新手。我创建了一个python模块来使用C++类。SWIG:无法使用双指针访问构造函数

我CPP头的代码是

GradedComplex.h:

class GradedComplex 
{ 
public: 
    typedef std::complex<double> dcomplex; 
    typedef Item<dcomplex> item_type; 
    typedef ItemComparator<dcomplex> comparator; 
    typedef std::set<item_type, comparator> grade_type; 

private: 
    int n_; 
    std::vector<grade_type *> grade_; 
    std::vector<double> thre_; 

public: 
    GradedComplex(int n, double *thre); 
    ~GradedComplex(); 

    void push(item_type item); 
    void avg(double *buf); 
}; 

而CPP代码

#include <iostream> 
#include "GradedComplex.h" 
using namespace std; 

GradedComplex::GradedComplex(int n, double *thre) 
{ 
    n_ = n; 
    for (int i = 0; i < n_; ++i) 
    { 
    thre_.push_back(thre[i]); 
    grade_.push_back(new grade_type()); 
    } 
} 

GradedComplex::~GradedComplex() 
{ 
    while (0 < grade_.size()) 
    { 
    delete grade_.back(); 
    grade_.pop_back(); 
    } 
} 

void GradedComplex::push(item_type item) 
{ 
    for (int i = 0; i < n_; ++i) 
    { 
    if (item.norm() < thre_[i]) 
    { 
     grade_[i]->insert(item); 
     break; 
    } 
    } 
} 

void GradedComplex::avg(double *buf) 
{ 
    for (int i = 0; i < n_; ++i) 
    { 
    int n = 0; 
    double acc = .0l; 
    for (grade_type::iterator it = grade_[i]->begin(); it != grade_[i]->end(); ++it) 
    { 
     acc += (*it).norm(); 
     ++n; 
    } 
    buf[i] = acc/n; 
    } 
} 

我痛饮接口文件是:

example.i

/* File: example.i */ 
%module example 
%{ 
#include "Item.h" 
#include "GradedComplex.h" 
#include "GradedDouble.h" 
%} 

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

我已经通过运行* python setup.py build_ext --inplace *这个命令生成了python模块。

,现在我想访问GradedComplex蟒蛇

(INT N,双* THRE)当我试图访问GradedComplex它显示 **类型错误:在方法 'new_GradedComplex',说法2的类型'双重'错误*

如何从python模块传递双指针?请帮我解决这个问题。

+0

*如何*你尝试调用'GradedComplex'?你通过了什么论点? – molbdnilo

+0

我已经通过这些LEVEL = 3,thre = [1.0,10.0,100.0] GradedComplex(LEVEL,thre) –

回答

2

这是简单的直接在构造函数中使用的载体,并充分利用痛饮的矢量支持优势:

.i文件:

%include <std_vector.i> 
%template(DoubleVector) std::vector<double>; 
%include "GradedComplex.h" 

.h

GradedComplex(const std::vector<double>& dbls); 

.cpp

GradedComplex::GradedComplex(const vector<double>& dbls) : thre_(dbls) 
{ 
} 

n_可以消失,因为thre_.size()是一回事。

与调用它:

c=Item.GradedComplex([1.2,3.4,5.6]) 

痛饮可以处理返回向量为好,这样avg可以是:

std::vector<double> GradedComplex::avg() { ... } 
+0

感谢您宝贵的时间.... –

+0

请参阅此链接http://stackoverflow.com/questions/13410691 /如何对通蟒蛇列表地址 –