1

我有一个 c++ 类

  • 将两个指向两个 numpy 数组的数据的指针存储为成员 ( m_ptrA, m_ptrB)
  • 公开一个函数来初始化指针 ( initPtrs)
  • doSomethingWithPtrs公开一个对指针 ( )进行操作的函数
class Foo
{
public:
  void initPtrs( py::array_t<int32_t  , py::array::c_style>  pyAryA,
                 py::array_t<float32_t, py::array::c_style>  pyAryB
                )
  {
    m_ptrA = (int32_t*)   pyAryA.request().ptr;
    m_ptrB = (float32_t*) pyAryB.request().ptr;
  }
  
  void doSomethingWithPtrs()
  {
     std::cout << m_ptrB[0] << std::endl; //Crashes sometimes here: Pointer m_ptrB is not valid.
  }
  
 private:
   int32_t*   m_ptrA;
   float32_t* m_ptrB;
};

我尝试使用 pybind11 将类及其函数绑定到 python:

PYBIND11_MODULE(bar,m)
{
py::class_<Foo>(m,"Foo")
  .def(py::init<>())
  .def( "init_ptrs"               , &Foo::initPtrs, py::keep_alive<1,2>(), py::keep_alive<1,3>() )
  .def( "do_something_with_ptrs"  , &Foo::doSomethingWithPtrs );
}

但是,在调用do_something_with_ptrsafter时init_ptrs,由于指针m_ptrB无效,以下程序有时会崩溃:

def test( aryA, torchTensorB ):
  my_foo = bar.Foo()
  my_foo.init_ptrs( aryA, torchTensorB.numpy() * 3840 )
  my_foo.do_something_with_ptrs()

aryA 是一个 int32 类型的 numpy 数组。 pyTensorB是 torch.float32 类型的 pytorch 张量。

我对 python/pybind 很陌生。任何帮助,将不胜感激。特别是,我不确定我py::keep_alive是否正确理解了这些陈述。

4

0 回答 0