在cython中将std :: vector <structints>从/转换为numpy.ndarray的最佳方法是什么?

时间:2018-02-26 02:13:21

标签: python c++ numpy vector cython

我使用cython来包装c ++库。要包含在c ++端的数据结构是:

struct StructInts {
    int a;
    int b;
    int c;
};
typedef std::vector<StructInts> VectorTris;

我希望将numpy.ndarray用作cython方面的接口(因为数据源为numpy.ndarray),具有以下想象功能:

cdef numpy.ndarray _from_vector_tris(VectorTris vector_tris):
    ...
    return _a_ndarray

cdef VectorTris _to_vector_tris(numpy.ndarray data_source):
    ...
    return _a_vector_tris

我尝试了从/到VectorTris(构建新的numpy.ndarrayVectorTris并填充它)的字段副本,如下所示:

cdef numpy.ndarray _from_vector_tris(VectorTris vector_tris):
    cdef int dim0 = vector_tris.size() * 3
    cdef numpy.ndarray _a_ndarray = numpy.empty(dim0, dtype=int)
    for i in range(vector_tris.size()):
        _a_ndarray[i*3]     = vector_tris[i].a
        _a_ndarray[i*3 + 1] = vector_tris[i].b
        _a_ndarray[i*3 + 2] = vector_tris[i].c
    return _a_ndarray

cdef VectorTris _to_vector_tris(numpy.ndarray data_source):
    # construct each StructInts and init .a, .b, .c with corresponding 
    # items in data_source, and then push_back into _a_vector_tris
    # the procedure seems like _from_vector_tris() but reversed
    return _a_vector_tris

它可以工作,但是对于大数据源,它太慢了

如何有效地在这两种数据结构之间进行转换? 谢谢!

0 个答案:

没有答案