为什么pybind11不能将PyObject* 识别为Python对象以及如何修复它?

ckx4rj1h  于 2023-06-04  发布在  Python
关注(0)|答案(1)|浏览(138)

我正在尝试使用以下C++代码构建一个库:

#include <pybind11/pybind11.h>

namespace py = pybind11;

PyObject* func() {
    return Py_BuildValue("iii", 1, 2, 3);
}

PYBIND11_MODULE(example, m) {
    m.def("func", &func);
}

但是当我尝试运行这个Python 3代码时:

import example
print(example.func())

它给我以下错误:

TypeError: Unregistered type : _object

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "<string>", line 1, in <module>
TypeError: Unable to convert function return value to a Python type! The signature was
        () -> _object

为什么会发生这种情况,以及如何解决?

nhaq1z21

nhaq1z211#

那么,首先,你想用你的函数做什么?强烈建议进行原始python API调用(Py_BuildValue,https://docs.python.org/3/c-api/arg.html#c.Py_BuildValue),这就是为什么你使用PyBind 11来处理这个问题。
你想用这条线做什么?

Py_BuildValue("iii", 1, 2, 3)

它看起来像你试图返回一个3 int的元组。也许这样的东西会起作用:

py::tuple func() {
    return py::make_tuple(1, 2, 3);
}

也就是说,我认为错误是由于Python不理解PyObject*是什么。因此,您需要使用py::class将PyObject公开给Python。我不确定这是否有意义,但我需要测试一下。
从我链接的文档来看,Py_BuildValue * 可能 * 返回一个元组。在这种情况下,我可以建议将返回值 Package 在py::tuple中。

相关问题