繁体   English   中英

在 C++ 中使用 Boost-Python 访问 Python 中定义的函数数组

[英]Use Boost-Python in C++ to Access to Array of Functions Defined in Python

我在 python 中有一组函数

Func[0](x,y,z)
Func[1](x,y,z)
...
Func[N](x,y,z)

我如何通过使用 boost-python 在 C++ 中加载函数指针数组来访问 C++ 中的 Func[0] 到 Func[N]。

typedef double (*CPP_Function)(double, double, double);
CPP_Function* Funcs; // Array of Function pointers

我希望能够打电话

for(int i=0; i<N; i++)
   a += (*CPP_Function[i])(0,0,0)

我尝试了 2 个函子,但没有成功

  Py_Initialize();

  bp::object main_module = bp::import("__main__");
  bp::object main_dict   = main_module.attr("__dict__");

  bp::exec(
    "def f1(x):\n"
    "  return  sin(x)*cos(x)\n"
    "def f2(x):\n"
    "  return  sin(x)*cos(x)\n"
    "f=[f1, f2]",
    main_dict
  );

  bp::object f = main_dict["f"];
  bp::object this_f = f[0];

  std::cout << bp::extract<double>(this_f(1.0)) << std::endl;

你的问题让我有点困惑:你有一个函数指针的 typedef,但你知道你将调用函子。 无论如何,您发布的代码不起作用,因为您忘记导入数学,请尝试

  bp::exec(
    "from math import *\n"
    "def f1(x):\n"
    "  return  sin(x)*cos(x)\n"
    "def f2(x):\n"
    "  return  sin(x)*cos(x)\n"
    "f=[f1, f2]",
    main_dict
  );

然后对于 c++ 类型,您可能需要使用:

  typedef std::function<double (double, double, double)> CPP_Function; // (a bad name)

使用标准库,它不会咬人:

  typedef vector< CPP_Function > CPP_Function_vector;

然后构建一个从 python 对象构造 CPP_Function 对象的适配器。 现在使用 lambda 函数非常容易。 全部一起:

#include <boost/python.hpp>

#include <functional>
#include <vector>

using namespace std;
namespace bp = boost::python;

typedef function<double(double, double, double)> CPP_Function;
typedef vector< CPP_Function > CPP_Function_vector; 

CPP_Function_vector convert_functions( bp::object const& functions ) 
{
    int l = bp::len( functions );
    CPP_Function_vector result;
    for (int i=0; i < l; i++ )
    {
        bp::object f = functions[i];
        result.push_back( [f]( double a, double b, double c)->double { return bp::extract<double>(f(a,b,c)); } );
    }
    return result;
}

int main( int argc, char* argv[] )
{

    Py_Initialize();

    bp::object main_module = bp::import("__main__");
    bp::object main_dict   = main_module.attr("__dict__");

    bp::exec(
        "from math import *\n"
        "def f1(x,y,z):\n"
        "  return  sin(x)*cos(y)*tan(z)\n"
        "def f2(x,y,z):\n"
        "  return  sin(x)*cos(z)\n"
        "f=[f1, f2]",
        main_dict
    );

    bp::object f = main_dict["f"];

    CPP_Function_vector function_vector = convert_functions( f );

    cout << function_vector[1](1.0, 0.2, 0.3) << endl;

    return 0;

}

暂无
暂无

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

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