fromdata.cpp 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. // Copyright Ankit Daftery 2011-2012.
  2. // Distributed under the Boost Software License, Version 1.0.
  3. // (See accompanying file LICENSE_1_0.txt or copy at
  4. // http://www.boost.org/LICENSE_1_0.txt)
  5. /**
  6. * @brief An example to show how to access data using raw pointers. This shows that you can use and
  7. * manipulate data in either Python or C++ and have the changes reflected in both.
  8. */
  9. #include <boost/python/numpy.hpp>
  10. #include <iostream>
  11. namespace p = boost::python;
  12. namespace np = boost::python::numpy;
  13. int main(int argc, char **argv)
  14. {
  15. // Initialize the Python runtime.
  16. Py_Initialize();
  17. // Initialize NumPy
  18. np::initialize();
  19. // Create an array in C++
  20. int arr[] = {1,2,3,4} ;
  21. // Create the ndarray in Python
  22. np::ndarray py_array = np::from_data(arr, np::dtype::get_builtin<int>() , p::make_tuple(4), p::make_tuple(4), p::object());
  23. // Print the ndarray that we just created, and the source C++ array
  24. std::cout << "C++ array :" << std::endl ;
  25. for (int j=0;j<4;j++)
  26. {
  27. std::cout << arr[j] << ' ' ;
  28. }
  29. std::cout << std::endl << "Python ndarray :" << p::extract<char const *>(p::str(py_array)) << std::endl;
  30. // Change an element in the python ndarray
  31. py_array[1] = 5 ;
  32. // And see if the C++ container is changed or not
  33. std::cout << "Is the change reflected in the C++ array used to create the ndarray ? " << std::endl ;
  34. for (int j = 0;j<4 ; j++)
  35. {
  36. std::cout << arr[j] << ' ' ;
  37. }
  38. // Conversely, change it in C++
  39. arr[2] = 8 ;
  40. // And see if the changes are reflected in the Python ndarray
  41. std::cout << std::endl << "Is the change reflected in the Python ndarray ?" << std::endl << p::extract<char const *>(p::str(py_array)) << std::endl;
  42. }