numpy array C api

后端 未结 2 1757
清酒与你
清酒与你 2020-12-31 19:23

I have a C++ function returning a std::vector and I want to use it in python, so I\'m using the C numpy api:

static PyObject *
py_integrate(PyObject *self, P         


        
2条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2020-12-31 20:25

    You will need to make a copy of the vector, since the vector will go out of scope and the memory will no longer be usable by the time you need it in Python (as stated by kwatford).

    One way to make the Numpy array you need (by copying the data) is:

    PyObject *out = nullptr;
    
    std::vector *vector = new std::vector();
    vector->push_back(1.);
    
    npy_intp size = {vector.size()};
    
    out = PyArray_SimpleNew(1, &size, NPY_DOUBLE);
    
    memcpy(PyArray_DATA((PyArrayObject *) out), vector.data(), vector.size());
    

提交回复
热议问题