如何使用 Boost.Python 将 python lambda func 传递给 c++ std::function<>



让我们考虑下一个例子:

#include <functional>
class Model
{
function<bool(const vector<double>&, float, float, float)> q_bifurcate_pointer;
}   

现在在c++ env中,我可以简单地将lambda值赋给q_bifurcate_pointer:

model.q_bifurcate_pointer = [](const vector<double>& a, float branch_lenght, float bifurcation_threshold, float bifurcation_min_dist)->bool
{
return (a.at(2) / a.at(0) <= bifurcation_threshold) 
&& branch_lenght >= bifurcation_min_dist;
};

接下来,我尝试使用'Boost '将该类导出到python。Python":

BOOST_PYTHON_MODULE(riversim)
{
class_<vector<double>> ("t_v_double")
.def(vector_indexing_suite<vector<double>>());
class_<Model>("Model")
.def_readwrite("q_bifurcate_pointer", &Model::q_bifurcate_pointer)
}

现在我们终于要解决这个问题了。在python中,我可以执行下面的行:

import riversim
model = riversim.Model()
model.q_bifurcate_pointer = lambda a, b, c, d: True
# or more complicated example with type specification
from typing import Callable
func: Callable[[riversim.t_v_double, float, float, float], bool] = lambda a, b, c, d: True
model.q_bifurcate_pointer = func

在这两种情况下,我得到下一个错误:

---------------------------------------------------------------------------
ArgumentError                             Traceback (most recent call last)
/home/oleg/Documents/riversim/riversimpy/histogram.ipynb Cell 2' in <module>
3 model = riversim.Model()
4 func: Callable[[riversim.t_v_double, float, float, float], bool] = lambda a, b, c, d: True
----> 5 model.q_bifurcate_pointer = func
ArgumentError: Python argument types in
None.None(Model, function)
did not match C++ signature:
None(River::Model {lvalue}, std::function<bool (std::vector<double, std::allocator<double> > const&, float, float, float)>)

那么,如何创建适当的lambda函数并将其传递给我的c++代码?

pythone中的Lambda表达式-这是字节码,c++需要机器码。只是谷歌类似于我的,但更普遍的问题在这里:https://stackoverflow.com/a/30445958/4437603