繁体   English   中英

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

[英]How to pass python lambda func to c++ std::function<> using Boost.Python

让我们考虑下一个例子:

#include <functional>

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

现在在 c++ 环境中,我可以简单地将 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM