1

我在python中有一系列函数

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

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

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;
4

1 回答 1

2

你的问题让我有点困惑:你有一个函数指针的 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;

}
于 2013-01-06T08:59:28.010 回答