[英]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.