title: Pybind11: Store pointer to numpy array data in c++ object
body: <p>I have a c++ class that</p>
  <ul>
  <li>stores two pointers to the data of two numpy arrays as members (<code>m_ptrA</code>, <code>m_ptrB</code>)</li>
  <li>exposes a function to initialize the pointers (<code>initPtrs</code>)</li>
  <li>exposes a function that operates on the pointers (<code>doSomethingWithPtrs</code>)</li>
  </ul>
  <pre><code>class Foo
  {
  public:
    void initPtrs( py::array_t&lt;int32_t  , py::array::c_style&gt;  pyAryA,
                   py::array_t&lt;float32_t, py::array::c_style&gt;  pyAryB
                  )
    {
      m_ptrA = (int32_t*)   pyAryA.request().ptr;
      m_ptrB = (float32_t*) pyAryB.request().ptr;
    }
    
    void doSomethingWithPtrs()
    {
       std::cout &lt;&lt; m_ptrB[0] &lt;&lt; std::endl; //Crashes sometimes here: Pointer m_ptrB is not valid.
    }
    
   private:
     int32_t*   m_ptrA;
     float32_t* m_ptrB;
  };
  </code></pre>
  <p>I tried to bind the class and its functions to python using pybind11:</p>
  <pre><code>PYBIND11_MODULE(bar,m)
  {
  py::class_&lt;Foo&gt;(m,&quot;Foo&quot;)
    .def(py::init&lt;&gt;())
    .def( &quot;init_ptrs&quot;               , &amp;Foo::initPtrs, py::keep_alive&lt;1,2&gt;(), py::keep_alive&lt;1,3&gt;() )
    .def( &quot;do_something_with_ptrs&quot;  , &amp;Foo::doSomethingWithPtrs );
  }
  </code></pre>
  <p>However, when calling <code>do_something_with_ptrs</code> after <code>init_ptrs</code>, the following program crashes sometimes, since the pointer <code>m_ptrB</code> is invalid:</p>
  <pre><code>def test( aryA, torchTensorB ):
    my_foo = bar.Foo()
    my_foo.init_ptrs( aryA, torchTensorB.numpy() * 3840 )
    my_foo.do_something_with_ptrs()
  </code></pre>
  <p><code>aryA</code>      is a numpy array of type int32.
  <code>pyTensorB</code> is a pytorch tensor of type torch.float32.</p>
  <p>I'm pretty new to python/pybind. Any help would be appreciated. In particular, I'm not sure if I understood the <code>py::keep_alive</code> statements correctly.</p>