title: Cast NumPy array to/from custom C++ Matrix-class using pybind11
body: <p>I am trying to wrap my C++ code using <code>pybind11</code>. In C++ I have a class <code>Matrix3D</code> which acts as a 3-D array (i.e. with shape <code>[n,m,p]</code>). It has the following basic signature:</p>
  
  <pre><code>template &lt;class T&gt; class Matrix3D
  {
  
    public:
  
      std::vector&lt;T&gt; data;
      std::vector&lt;size_t&gt; shape;
      std::vector&lt;size_t&gt; strides;
  
      Matrix3D&lt;T&gt;();
      Matrix3D&lt;T&gt;(std::vector&lt;size_t&gt;);
      Matrix3D&lt;T&gt;(const Matrix3D&lt;T&gt;&amp;);
  
      T&amp; operator() (int,int,int);
  
  };
  </code></pre>
  
  <p>To minimize the wrapper code I would like to cast this class directly to and from a NumPy-array (copies are no problem). For example, I would like to directly wrap a function of the following signature:</p>
  
  <pre><code>Matrix3D&lt;double&gt; func ( const Matrix3D&lt;double&gt;&amp; );
  </code></pre>
  
  <p>using the wrapper code</p>
  
  <pre><code>#include &lt;pybind11/pybind11.h&gt;
  #include &lt;pybind11/stl.h&gt;
  #include &lt;pybind11/numpy.h&gt;
  
  namespace py = pybind11;
  
  PYBIND11_PLUGIN(example) {
    py::module m("example", "Module description");
    m.def("func", &amp;func, "Function description" );
    return m.ptr();
  }
  </code></pre>
  
  <p>Currently I have another function in-between that accepts and returns <code>py::array_t&lt;double&gt;</code>. But I would like to avoid having to write a wrapper function for each function by replacing it by some template.</p>
  
  <p>This has been done for the <code>Eigen</code>-library (for arrays and (2-D) matrices). But the code is too involved for me to derive my own code from. Plus, I really only need to wrap only one, simple, class.</p>