[C++-sig] create boost array from a Numpy PyArray without copying data?
Sebastian Walter
walter at mathematik.hu-berlin.de
Mon Jan 19 13:16:10 CET 2009
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
Hello,
On the C++ side I have a raw pointer: double *x;
I'd like to change its values from within Python by using Numpy.
Example code can be found below.
My approach is
1) make PyArray from existing data *x with PyArray_SimpleNewFromData
2) create a boost array from the PyArray.
My question is:
How can I create a
boost::python::numeric::array from a Numpy Pyarray without copying data?
Here my best shot... (compiles and runs but copies the data)
- ----------------- test.cpp ------------------
#define PY_ARRAY_UNIQUE_SYMBOL PyArrayHandle
#include <iostream>
#include <boost/python.hpp>
#include <numpy/noprefix.h>
using namespace std;
using namespace boost;
using namespace boost::python;
using namespace boost::python::numeric;
array test_function(){
int N = 3;
double x[] = {1.,2.,3.};
array numpy_x(static_cast<array>(handle<>(PyArray_SimpleNewFromData(1,
&N, PyArray_DOUBLE, x))));
double *y = static_cast<double*> PyArray_DATA(numpy_x.ptr());
y[0] = 37.;
for(int n = 0; n<N; ++n){
cout<<"numpy_x[n]="<<y[n]<<"\t\t"<<"x[n]="<<x[n]<<endl;
}
return numpy_x;
}
BOOST_PYTHON_MODULE(_test)
{
import_array();
array::set_module_and_type("numpy", "ndarray");
def("test_function", test_function);
}
- ----------- test.py -----------------
from _test import *
if __name__ == "__main__":
print test_function()
- --------------- shell output --------------------
$python test.py
numpy_x[n]=37 x[n]=1
numpy_x[n]=2 x[n]=2
numpy_x[n]=3 x[n]=3
[ 37. 2. 3.]
It would be great if anyone knew the answer to my problem.
regards,
Sebastian Walter
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v2.0.4-svn0 (GNU/Linux)
Comment: Using GnuPG with SUSE - http://enigmail.mozdev.org
iD8DBQFJdG8K9PBA5IG0h0ARAoOPAJ0Wl/hexJymtrrxmwRMuewSxjuG3wCgka7o
Q90ZJlkWV34VfHcrpQqlrGA=
=kEyK
-----END PGP SIGNATURE-----
More information about the Cplusplus-sig
mailing list