c++ - 痛饮 : Unable to access constructor with double pointer

标签 c++ python swig

我是 SWIG 的新手。我创建了一个 python 模块来使用 C++ 类。

我的cpp头代码是

渐变复杂.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;
  }
}

我的 SWIG 接口(interface)文件是:

例子.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 模块。

现在我想从 python 访问 GradedComplex(int n, double *thre)

当我尝试访问 GradedComplex 时,它显示 **TypeError:在方法“new_GradedComplex”中,参数 2 的类型为“double 错误*

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

最佳答案

直接在构造函数中使用 vector 并利用 SWIG 的 vector 支持更简单:

.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])

SWIG 也可以处理返回 vector ,所以 avg 可以是:

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

关于c++ - 痛饮 : Unable to access constructor with double pointer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13392512/

相关文章:

c++ - 如何使用现有的 Sqlite 数据库部署 Qt 应用程序?

c++ - 我的循环缓冲区出了什么问题

python - 从间隔列表中确定值的位置(综合解决方案)

python - 找不到页面 (404) 请求方法 : POST Request URL: http://127. 0.0.1:8000/accounts/signup/signup

java - 将 C++ 函数的返回类型映射到 Java 中的 byte[][]

c++ - SWIG 接口(interface)文件问题

c++ - 覆盖 vector 的第一个元素会改变 vector 最后一个元素的内容

c++ - collect2.exe [错误] ld 返回 1 退出状态

python - 在 Python 中检查 __debug__ 和其他一些条件

c# - 使用 Swig 为 C++ 代码构建 C# 包装器时,是否可以向现有方法添加代码?