我正在尝试围绕 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/