4 Here is a brief tutorial to show how to create ndarrays with built-in python data types, and extract the types and values of member variables
6 Like before, first get the necessary headers, setup the namespaces and initialize the Python runtime and numpy module::
8 #include <boost/python/numpy.hpp>
11 namespace p = boost::python;
12 namespace np = boost::python::numpy;
14 int main(int argc, char **argv)
19 Next, we create the shape and dtype. We use the get_builtin method to get the numpy dtype corresponding to the builtin C++ dtype
20 Here, we will create a 3x3 array passing a tuple with (3,3) for the size, and double as the data type ::
22 p::tuple shape = p::make_tuple(3, 3);
23 np::dtype dtype = np::dtype::get_builtin<double>();
24 np::ndarray a = np::zeros(shape, dtype);
26 Finally, we can print the array using the extract method in the python namespace.
27 Here, we first convert the variable into a string, and then extract it as a C++ character array from the python string using the <char const \* > template ::
29 std::cout << "Original array:\n" << p::extract<char const *>(p::str(a)) << std::endl;
31 We can also print the dtypes of the data members of the ndarray by using the get_dtype method for the ndarray ::
33 std::cout << "Datatype is:\n" << p::extract<char const *>(p::str(a.get_dtype())) << std::endl ;
35 We can also create custom dtypes and build ndarrays with the custom dtypes
37 We use the dtype constructor to create a custom dtype. This constructor takes a list as an argument.
39 The list should contain one or more tuples of the format (variable name, variable type)
41 So first create a tuple with a variable name and its dtype, double, to create a custom dtype ::
43 p::tuple for_custom_dtype = p::make_tuple("ha",dtype) ;
45 Next, create a list, and add this tuple to the list. Then use the list to create the custom dtype ::
47 p::list list_for_dtype ;
48 list_for_dtype.append(for_custom_dtype) ;
49 np::dtype custom_dtype = np::dtype(list_for_dtype) ;
51 We are now ready to create an ndarray with dimensions specified by \*shape\* and of custom dtpye ::
53 np::ndarray new_array = np::zeros(shape,custom_dtype);