【问题标题】:Pybind11 pointer referencePybind11 指针引用
【发布时间】:2022-07-06 23:09:56
【问题描述】:

我正在尝试在 python 中使用一个将指针作为参数的 c++ 函数。 对于外观,我在 python 中使用 pybind11 和 ctypes 来创建指针。

但是,我在 python 中获得的地址不等于在 c++ 中的地址。 我在项目的后期确实需要一个变量的地址,但我无法通过返回来获取它,因为该函数已经返回了其他东西。

c++函数

  void myFunc(double* ptr, double value)
  {
      *ptr = value;

      std::cout << "ptr value:\t\t" << *ptr << std::endl;
      std::cout << "ptr adress:\t\t" << ptr << std::endl;
  };

pybind 代码

m.def("myFunc",
    [](double* ptr,
        double value) {
            myFunc(ptr, value);
    }, "funtion to test stuff out");

python 代码

ptr_value = ctypes.c_double()
ptr_addressof = ctypes.addressof(ptr_value)
ptr_object_pointer = pointer(ptr_value)
ptr_pointer = ctypes.cast(ptr_object_pointer, ctypes.c_void_p).value
print(f'python ptr using addressof(ptr_value):\t\t{ptr_addressof}')
print(f'python adress using ctypes.cast:\t\t{ptr_pointer}')
print(f'python ptr object using pointer(ptr_value):\t{ptr_object_pointer}')

value = 14.0
myFunc(ptr_addressof, value)

输出

python ptr using addressof(ptr_value):          2784493684616
python adress using ctypes.cast:                2784493684616
python ptr object using pointer(ptr_value):     <__main__.LP_c_double object at 0x0000028850C1C8C0>
ptr value:              14
ptr adress:             000000CC2D3EE490

如何在 c++ 和 python 中获得相同的地址?

【问题讨论】:

  • 为什么要同时使用 pubind11 和 ctypes?

标签: python c++ ctypes pybind11


【解决方案1】:

pybind11 中的指针函数参数不能这样工作。

这是你应该如何使用myFunc

x = 0.123
myFunc(x, 42)   # modifies x
print(x)        # prints 42

换句话说,它只是一个外参数,你不应该在 Python 端使用指针。

据我所知,没有简单的方法可以让这个模型使用从ctypes 获得的指针值。

我不知道为什么在上帝的绿色地球上你同时需要pybind11ctypes,但如果你这样做,请将指针包装在 C++ 类中并传递该类的对象。

【讨论】:

    猜你喜欢
    • 2021-09-18
    • 2020-01-19
    • 2018-08-18
    • 1970-01-01
    • 1970-01-01
    • 2021-07-03
    • 2022-07-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多