fromdata.rst 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. How to access data using raw pointers
  2. =====================================
  3. One of the advantages of the ndarray wrapper is that the same data can be used in both Python and C++ and changes can be made to reflect at both ends.
  4. The from_data method makes this possible.
  5. Like before, first get the necessary headers, setup the namespaces and initialize the Python runtime and numpy module::
  6. #include <boost/python/numpy.hpp>
  7. #include <iostream>
  8. namespace p = boost::python;
  9. namespace np = boost::python::numpy;
  10. int main(int argc, char **argv)
  11. {
  12. Py_Initialize();
  13. np::initialize();
  14. Create an array in C++ , and pass the pointer to it to the from_data method to create an ndarray::
  15. int arr[] = {1,2,3,4,5};
  16. np::ndarray py_array = np::from_data(arr, np::dtype::get_builtin<int>(),
  17. p::make_tuple(5),
  18. p::make_tuple(sizeof(int)),
  19. p::object());
  20. Print the source C++ array, as well as the ndarray, to check if they are the same::
  21. std::cout << "C++ array :" << std::endl;
  22. for (int j=0;j<4;j++)
  23. {
  24. std::cout << arr[j] << ' ';
  25. }
  26. std::cout << std::endl
  27. << "Python ndarray :" << p::extract<char const *>(p::str(py_array)) << std::endl;
  28. Now, change an element in the Python ndarray, and check if the value changed correspondingly in the source C++ array::
  29. py_array[1] = 5 ;
  30. std::cout << "Is the change reflected in the C++ array used to create the ndarray ? " << std::endl;
  31. for (int j = 0; j < 5; j++)
  32. {
  33. std::cout << arr[j] << ' ';
  34. }
  35. Next, change an element of the source C++ array and see if it is reflected in the Python ndarray::
  36. arr[2] = 8;
  37. std::cout << std::endl
  38. << "Is the change reflected in the Python ndarray ?" << std::endl
  39. << p::extract<char const *>(p::str(py_array)) << std::endl;
  40. }
  41. As we can see, the changes are reflected across the ends. This happens because the from_data method passes the C++ array by reference to create the ndarray, and thus uses the same locations for storing data.