File: fromdata.rst

package info (click to toggle)
boost1.83 1.83.0-5
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 545,632 kB
  • sloc: cpp: 3,857,086; xml: 125,552; ansic: 34,414; python: 25,887; asm: 5,276; sh: 4,799; ada: 1,681; makefile: 1,629; perl: 1,212; pascal: 1,139; sql: 810; yacc: 478; ruby: 102; lisp: 24; csh: 6
file content (56 lines) | stat: -rw-r--r-- 2,079 bytes parent folder | download | duplicates (9)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
How to access data using raw pointers
=====================================

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.
The from_data method makes this possible.

Like before, first get the necessary headers, setup the namespaces and initialize the Python runtime and numpy module::

  #include <boost/python/numpy.hpp>
  #include <iostream>

  namespace p = boost::python;
  namespace np = boost::python::numpy;

  int main(int argc, char **argv)
  {
    Py_Initialize();
    np::initialize();

Create an array in C++ , and pass the pointer to it to the from_data method to create an ndarray::

    int arr[] = {1,2,3,4,5};
    np::ndarray py_array = np::from_data(arr, np::dtype::get_builtin<int>(),
                                         p::make_tuple(5),
					 p::make_tuple(sizeof(int)),
					 p::object());

Print the source C++ array, as well as the ndarray, to check if they are the same::

    std::cout << "C++ array :" << std::endl;
    for (int j=0;j<4;j++)
    {
      std::cout << arr[j] << ' ';
    }
    std::cout << std::endl
              << "Python ndarray :" << p::extract<char const *>(p::str(py_array)) << std::endl;

Now, change an element in the Python ndarray, and check if the value changed correspondingly in the source C++ array::

    py_array[1] = 5 ;
    std::cout << "Is the change reflected in the C++ array used to create the ndarray ? " << std::endl;
    for (int j = 0; j < 5; j++)
    {
      std::cout << arr[j] << ' ';
    }

Next, change an element of the source C++ array and see if it is reflected in the Python ndarray::

    arr[2] = 8;
    std::cout << std::endl
              << "Is the change reflected in the Python ndarray ?" << std::endl
	      << p::extract<char const *>(p::str(py_array)) << std::endl;
  }

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.