Skip to content

Commit 4ec94c6

Browse files
committed
Add example (wrap.py) to demonstrate how to wrap simple functions that operate on C arrays into functions that operate on NumPy arrays (boostorg#6).
1 parent a35cbd1 commit 4ec94c6

2 files changed

Lines changed: 128 additions & 0 deletions

File tree

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,3 +8,4 @@ libs/numpy/example/fromdata
88
libs/numpy/example/ndarray
99
libs/numpy/example/simple
1010
libs/numpy/example/ufunc
11+
libs/numpy/example/wrap

libs/numpy/example/wrap.cpp

Lines changed: 127 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,127 @@
1+
/**
2+
* A simple example showing how to wrap a couple of C++ functions that
3+
* operate on 2-d arrays into Python functions that take NumPy arrays
4+
* as arguments.
5+
*
6+
* If you find have a lot of such functions to wrap, you may want to
7+
* create a C++ array type (or use one of the many existing C++ array
8+
* libraries) that maps well to NumPy arrays and create Boost.Python
9+
* converters. There's more work up front than the approach here,
10+
* but much less boilerplate per function. See the "Gaussian" example
11+
* included with Boost.NumPy for an example of custom converters, or
12+
* take a look at the "ndarray" project on GitHub for a more complete,
13+
* high-level solution.
14+
*
15+
* Note that we're using embedded Python here only to make a convenient
16+
* self-contained example; you could just as easily put the wrappers
17+
* in a regular C++-compiled module and imported them in regular
18+
* Python. Again, see the Gaussian demo for an example.
19+
*/
20+
21+
#include <boost/numpy.hpp>
22+
#include <boost/scoped_array.hpp>
23+
#include <iostream>
24+
25+
namespace p = boost::python;
26+
namespace np = boost::numpy;
27+
28+
// This is roughly the most efficient way to write a C/C++ function that operates
29+
// on a 2-d NumPy array - operate directly on the array by incrementing a pointer
30+
// with the strides.
31+
void fill1(double * array, int rows, int cols, int row_stride, int col_stride) {
32+
double * row_iter = array;
33+
double n = 0.0; // just a counter we'll fill the array with.
34+
for (int i = 0; i < rows; ++i, row_iter += row_stride) {
35+
double * col_iter = row_iter;
36+
for (int j = 0; j < cols; ++j, col_iter += col_stride) {
37+
*col_iter = ++n;
38+
}
39+
}
40+
}
41+
42+
// Here's a simple wrapper function for fill1. It requires that the passed
43+
// NumPy array be exactly what we're looking for - no conversion from nested
44+
// sequences or arrays with other data types, because we want to modify it
45+
// in-place.
46+
void wrap_fill1(np::ndarray const & array) {
47+
if (array.get_dtype() != np::dtype::get_builtin<double>()) {
48+
PyErr_SetString(PyExc_TypeError, "Incorrect array data type");
49+
p::throw_error_already_set();
50+
}
51+
if (array.get_nd() != 2) {
52+
PyErr_SetString(PyExc_TypeError, "Incorrect number of dimensions");
53+
p::throw_error_already_set();
54+
}
55+
fill1(reinterpret_cast<double*>(array.get_data()),
56+
array.shape(0), array.shape(1),
57+
array.strides(0) / sizeof(double), array.strides(1) / sizeof(double));
58+
}
59+
60+
// Another fill function that takes a double**. This is less efficient, because
61+
// it's not the native NumPy data layout, but it's common enough in C/C++ that
62+
// it's worth its own example. This time we don't pass the strides, and instead
63+
// in wrap_fill2 we'll require the C_CONTIGUOUS bitflag, which guarantees that
64+
// the column stride is 1 and the row stride is the number of columns. That
65+
// restricts the arrays that can be passed to fill2 (it won't work on most
66+
// subarray views or transposes, for instance).
67+
void fill2(double ** array, int rows, int cols) {
68+
double n = 0.0; // just a counter we'll fill the array with.
69+
for (int i = 0; i < rows; ++i) {
70+
for (int j = 0; j < cols; ++j) {
71+
array[i][j] = ++n;
72+
}
73+
}
74+
}
75+
// Here's the wrapper for fill2; it's a little more complicated because we need
76+
// to check the flags and create the array of pointers.
77+
void wrap_fill2(np::ndarray const & array) {
78+
if (array.get_dtype() != np::dtype::get_builtin<double>()) {
79+
PyErr_SetString(PyExc_TypeError, "Incorrect array data type");
80+
p::throw_error_already_set();
81+
}
82+
if (array.get_nd() != 2) {
83+
PyErr_SetString(PyExc_TypeError, "Incorrect number of dimensions");
84+
p::throw_error_already_set();
85+
}
86+
if (!(array.get_flags() & np::ndarray::C_CONTIGUOUS)) {
87+
PyErr_SetString(PyExc_TypeError, "Array must be row-major contiguous");
88+
p::throw_error_already_set();
89+
}
90+
double * iter = reinterpret_cast<double*>(array.get_data());
91+
int rows = array.shape(0);
92+
int cols = array.shape(1);
93+
boost::scoped_array<double*> ptrs(new double*[rows]);
94+
for (int i = 0; i < rows; ++i, iter += cols) {
95+
ptrs[i] = iter;
96+
}
97+
fill2(ptrs.get(), array.shape(0), array.shape(1));
98+
}
99+
100+
BOOST_PYTHON_MODULE(example) {
101+
np::initialize(); // have to put this in any module that uses Boost.NumPy
102+
p::def("fill1", wrap_fill1);
103+
p::def("fill2", wrap_fill2);
104+
}
105+
106+
int main(int argc, char **argv)
107+
{
108+
// This line makes our module available to the embedded Python intepreter.
109+
PyImport_AppendInittab("example", &initexample);
110+
111+
// Initialize the Python runtime.
112+
Py_Initialize();
113+
114+
PyRun_SimpleString(
115+
"import example\n"
116+
"import numpy\n"
117+
"z1 = numpy.zeros((5,6), dtype=float)\n"
118+
"z2 = numpy.zeros((4,3), dtype=float)\n"
119+
"example.fill1(z1)\n"
120+
"example.fill2(z2)\n"
121+
"print z1\n"
122+
"print z2\n"
123+
);
124+
Py_Finalize();
125+
}
126+
127+

0 commit comments

Comments
 (0)