简体   繁体   English

使用SWIG包装C ++ <vector> 作为python NumPy数组

[英]Use SWIG to wrap C++ <vector> as python NumPy array

I have a C++ library that defines the following (and more like them) types: 我有一个C ++库,它定义了以下(以及更多类似的)类型:

typedef std::vector< double > DoubleVec;

typedef std::vector< DoubleVec > DoubleVecVec;

typedef std::vector< int > IntVec;

typedef std::vector< IntVec > IntVecVec;

I am trying to create a python interface to a library that handles objects like that. 我正在尝试为处理此类对象的库创建python接口。 As the title states, I would like my interface to convert to/from C++ std::vector and numpy ndarray . 如标题所述,我希望我的界面与C ++ std::vector和numpy ndarray

I have seen both numpy.i provided by the numpy people and std_vector.i from the SWIG people. 我已经看到了numpy员工提供的numpy.i和来自SWIG员工的std_vector.i The problems are that numpy.i was created to handle C/C++ arrays (not C++ vectors) and std_vector.i doesn't do conversion directly to/from numpy arrays. 问题在于创建numpy.i来处理C / C ++数组(不是C ++向量),而std_vector.i并不直接与numpy数组进行转换。

Any ideas? 有任何想法吗?

I have seen that the FEniCS project has done something like this, but their project is so large that I am having a hard time finding out just how they do this specific task. 我已经看到FEniCS项目已经做了类似的事情,但是他们的项目是如此之大,以至于我很难找出他们是如何完成这项特定任务的。

Try this as a starting point. 以此为起点。

%include "numpy.i"

%apply (size_t DIM1, double* IN_ARRAY1) {(size_t len_, double* vec_)}

%rename (foo) my_foo;
%inline %{
int my_foo(size_t len_, double* vec_) {
    std::vector<double> v;
    v.insert(v.end(), vec_, vec_ + len_);
    return foo(v);
}
%}

%apply (size_t DIM1, size_t DIM2, double* IN_ARRAY2) {(size_t len1_, size_t len2_, double* vec_)}

%rename (bar) my_bar;
%inline %{
int my_bar(size_t len1_, size_t len2_, double* vec_) {
    std::vector< std::vector<double> > v (len1_);
    for (size_t i = 0; i < len1_; ++i) {
        v[i].insert(v[i].end(), vec_ + i*len2_, vec_ + (i+1)*len2_);
    }
    return bar(v);
}
%}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM