SWIG : Unable to access constructor with double pointer

我的未来我决定 提交于 2020-01-14 03:30:28

问题


I am new to SWIG. I have created a python module to use c++ classes.

My cpp header code is

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);
};

And CPP code is

#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;
  }
}

My SWIG interface file is :

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

I have generated python module by running *python setup.py build_ext --inplace* this command.

And now I want to access GradedComplex(int n, double *thre) from python

When I tried to access GradedComplex it shows **TypeError: in method 'new_GradedComplex', argument 2 of type 'double ' error*

How do I pass double pointer from python module? Please help me to sort this issue.


回答1:


It is simpler to use a vector directly in the constructor and take advantage of SWIG's vector support:

In the .i file:

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

In the .h:

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

In the .cpp:

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

n_ can go away, since thre_.size() is the same thing.

Call it with:

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

SWIG can handle returning vectors as well, so avg can be:

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


来源:https://stackoverflow.com/questions/13392512/swig-unable-to-access-constructor-with-double-pointer

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!