我无法将类方法的输入(输入:单独类的特定实例)返回到Python.绑定被编译,我可以使用在Python中生成的模块.但是,类方法应该返回它所允许的相同实例(经过一些处理之后).
使用Obstacle
类作为输入.ObstacleProcess
类有一个处理输入(Obstacle
的实例)的方法(Python:__call__
/C++:operator_py
).下面的Python代码显示返回Obstacle
的不同实例:
import example
obstacle_1 = example.Obstacle()
obstacle_2 = example.Obstacle()
obstacles = [obstacle_1, obstacle_2]
print(obstacles)
params = example.Params()
obstacle_process = example.ObstacleProcess(params)
obstacles = obstacle_process(obstacles)
print(obstacles)
第一个打印返回:[<example.Obstacle object at 0x7fb65271e1b0>, <example.Obstacle at 0x7fb652735070>]
,而第二个打印返回:[<example.Obstacle at 0x7fb652734670>, <example.Obstacle object at 0x7fb652735230>]
.
这不是期望的输出,因为obstacle_1
最初位于0x7fb65271e1b0
,而在operator()
/__call__
调用之后,它位于0x7fb652734670
.我希望obstacle_1
保留其初始地址0x7fb65271e1b0
,即使在另一个类(ObstacleProcess
)处理了obstacle_1
之后也是如此.
以下代码显示源代码绑定了pybind11:
// pybind11 binding
py::class_<Obstacle, std::shared_ptr<Obstacle>>(m, "Obstacle")
.def(py::init<>());
py::class_<ObstacleProcess>(m, "ObstacleProcess")
.def(py::init<
const Params&>()
)
.def("__call__", &ObstacleProcess::operator_py<Params>, py::return_value_policy::reference);
下一块显示了如何在源代码中实现operator_py
:
template <Params>
std::vector<Obstacle>& operator_py(
std::vector<Obstacle>& obstacles,
const Params ¶meters
)
{
...
return obstacles
}
我试过用std::shared_ptr<Obstacle>
和不用std::shared_ptr<Obstacle>
.当前实现的结果与根本不使用shared_ptr
的结果相同,因此我实现shared_ptr
的方式有问题.我try 使用PYBIND11_MAKE_OPAQUE(std::shared_ptr<std::vector<Obstacle>>);
,但我的实现并没有改变结果.
我没有试过用pybind11 — smart_holder branch
,也许这次要用这个 twig 呢?