January 4th 2008

Transforming a C++ vector into a Numpy array

1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5.00 out of 5)
Loading ... Loading ...

This question was asked on the Scipy mailing-list last year (well, one week ago). Nathan Bell proposed a skeleton that I used to create an out typemap for SWIG.

1
2
3
4
5
6
%typemap(out) std::vector<double> {
    int length = $1.size();
    $result = PyArray_FromDims(1, &amp;length, PyArray_DOUBLE);
    memcpy(PyArray_DATA($result),&amp;((*(&amp;$1))[0]),sizeof(double)*length);
}
</double>

This typemap uses obviously Numpy, so don’t forget to initialize the module and to import it. Then there is a strange instruction in memcpy. &((*(&$1))[0]) takes the address of the array of the vector, but as it is wrapped by SWIG, one has to get to the std::vector by dereferencing the SWIG wrapper. Then one can get the first element in the vector and take the address.

Tags: , , , ,

No Comments yet »

Trackback URI | Comments RSS

Leave a Reply

« | »

  • Categories

  • Archives

  • Advertisement

Performance Optimization WordPress Plugins by W3 EDGE