]> git.proxmox.com Git - ceph.git/blob - ceph/src/boost/libs/python/example/numpy/fromdata.cpp
add subtree-ish sources for 12.0.3
[ceph.git] / ceph / src / boost / libs / python / example / numpy / fromdata.cpp
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 /**
7 * @brief An example to show how to access data using raw pointers. This shows that you can use and
8 * manipulate data in either Python or C++ and have the changes reflected in both.
9 */
10
11 #include <boost/python/numpy.hpp>
12 #include <iostream>
13
14 namespace p = boost::python;
15 namespace np = boost::python::numpy;
16
17
18 int main(int argc, char **argv)
19 {
20 // Initialize the Python runtime.
21 Py_Initialize();
22 // Initialize NumPy
23 np::initialize();
24 // Create an array in C++
25 int arr[] = {1,2,3,4} ;
26 // Create the ndarray in Python
27 np::ndarray py_array = np::from_data(arr, np::dtype::get_builtin<int>() , p::make_tuple(4), p::make_tuple(4), p::object());
28 // Print the ndarray that we just created, and the source C++ array
29 std::cout << "C++ array :" << std::endl ;
30 for (int j=0;j<4;j++)
31 {
32 std::cout << arr[j] << ' ' ;
33 }
34 std::cout << std::endl << "Python ndarray :" << p::extract<char const *>(p::str(py_array)) << std::endl;
35 // Change an element in the python ndarray
36 py_array[1] = 5 ;
37 // And see if the C++ container is changed or not
38 std::cout << "Is the change reflected in the C++ array used to create the ndarray ? " << std::endl ;
39 for (int j = 0;j<4 ; j++)
40 {
41 std::cout << arr[j] << ' ' ;
42 }
43 // Conversely, change it in C++
44 arr[2] = 8 ;
45 // And see if the changes are reflected in the Python ndarray
46 std::cout << std::endl << "Is the change reflected in the Python ndarray ?" << std::endl << p::extract<char const *>(p::str(py_array)) << std::endl;
47
48 }