1

I'm using cython to wrap a c++ library. A data structure to be wrapped in c++ side is:

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

I'm hope for using numpy.ndarray as an interface in cython side(because the data source is numpy.ndarray), with imagined functions like:

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

I tried field by field copy from/to VectorTris(construct new numpy.ndarray or VectorTris and fill it) like this:

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

It works but with large data source, it's too slow

How to convert between these two data structures efficiently? Thanks !

  • I think you can `memcpy` data between the vector and ndarray. To get raw data pointer of ndarray, you can use `arr.data`, to get raw point of vector, https://stackoverflow.com/questions/6485496/how-to-get-stdvector-pointer-to-the-raw-data – HYRY Feb 26 '18 at 04:18
  • It is probably good to include your current version as starting point for the discussion. Also „large“ and „too slow“ can mean a lot of things and it would make the question clearer if they where numbers or ranges of interest – ead Feb 26 '18 at 05:02
  • I'm trying to call `vector.data()` to get the internal pointer and fill the `ndarray` with method `PyArray_SimpleNewFromData` by passing that pointer directly. But I don't know if c++ `struct` `StructInts`'s memory layout is same with raw `int[3]`, I'll try and make tests. Thanks! @HYRY – user9410891 Feb 26 '18 at 08:50

0 Answers0