c++ - 用 swig 包裹 boost::ublas

标签 c++ python boost swig

我正在尝试围绕 numpy 和 boost::ublas 层传递数据。我 写了一个超薄包装器,因为 swig 无法解析 ublas' 标题正确。代码如下所示

#include <boost/numeric/ublas/vector.hpp>
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/lexical_cast.hpp>
#include <algorithm>
#include <sstream>
#include <string>

using std::copy;
using namespace boost;

typedef boost::numeric::ublas::matrix<double> dm;
typedef boost::numeric::ublas::vector<double> dv;

class dvector : public dv{
 public:
 dvector(const int rhs):dv(rhs){;};
 dvector();
 dvector(const int size, double* ptr):dv(size){
   copy(ptr, ptr+sizeof(double)*size, &(dv::data()[0]));
 }
 ~dvector(){}
};

使用类似于 SWIG 的界面

%apply(int DIM1, double* INPLACE_ARRAY1) {(const int size, double* ptr)}
class dvector{
 public:
 dvector(const int rhs);
 dvector();
 dvector(const int size, double* ptr);
       %newobject toString;
 char* toString();
       ~dvector();
};

我已经通过 gcc 4.3 和 vc++9.0 成功地编译了它们。然而 当我简单地运行时

a = dvector(array([1.,2.,3.]))

它给我一个段错误。这是我第一次将 swigh 与 numpy 一起使用 并没有完全理解数据转换和 内存缓冲区传递。有没有人看到我有明显的东西 错过了?我试图通过调试器进行跟踪,但它在 python.exe 的组合中崩溃了。我不知道这是一个 swig 问题还是我的简单包装器的问题。任何事情都值得赞赏。

最佳答案

您可能有兴趣查看 pyublas模块。它无缝地在 numpy 数组和 ublas 数据类型之间进行转换,无需复制。

关于c++ - 用 swig 包裹 boost::ublas,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2755352/

相关文章:

c++ - 如何在 Xcode 中使用 boost::multiprecision::float128

c++ - 如何判断翻译单元是否正在使用分段堆栈进行编译

c++ - 模板类 C++ - 排除某些类型

python - 为什么 SQL Server 返回 0.759999 而 MySQL 返回 0.76?

python - 如何创建一个字典,其中键是列表中的元素,值是从 1 到 n 的数字?

python - 如何制作一个使用运算符作为输入的计算器功能?

c++ - 有没有办法在 Boost Asio 中异步等待 future ?

c++ - Boost BCCL 容器算法工作示例

c++ - Visual Build专业编译错误?

c++ - 我的简单 C 程序出现内存错误