使用Boost.Python进行Python到C++函数的转换

Ale*_*lex 8 c++ python boost-python

我有一堆用C++编写的类和API,并在Boost.Python的帮助下暴露给Python

我目前正在研究创建以下架构的可能性.
在python中:

from boostPythonModule import *
AddFunction( boostPythonObject.Method1, args )
AddFunction( boostPythonObject.Method2, args )
AddFunction( boostPythonObject.Method2, args )
RunAll( ) # running is done by C++
Run Code Online (Sandbox Code Playgroud)

在C++中:

void AddFunction( boost::object method,  boost::object args )
{
    /// 1. Here i need to extract a real pointer to a function
    /// 2. Make argument and type checking for a function under method
    /// 3. Unpack all arguments to native types
    /// 4. Store the pointer to a function somewhere in local storage
}

void RunAll( )
{
    /// 1. run all previously stored functions and arguments for them
}
Run Code Online (Sandbox Code Playgroud)

基本上我试图将所有功能放到我的程序的本机部分.问题是我不确定是否有可能从Boost metainfo中提取所有必需的数据以通用方式执行此操作 - 在编译时我不应该知道我将调用哪些函数以及它们接受哪些参数.

几个问题:
1.我可以访问任何共享的Python信息表来检查这些东西吗?
2. Boost.Python进行类型参数检查.可以单独重复使用吗?

让我知道你的想法.

谢谢

Bas*_*evs 1

我会考虑在 python 级别缓存函数及其参数 - 使用教程的关键字参数部分中的最新形式保存参数,并稍后调用您的 C++ 函数解包保存的参数在 python 级别完成的解包将使您免受任何 boost 类型安全复杂性的影响(所有类型检查将在 RunAll 阶段完成,这会导致速度变慢且安全性降低)。

速度优化方法是实现一个具有通用接口的 C++ 类,该接口可以接受支持给定参数的函数调用,并在内部缓存它们的值以供以后运行时使用。

struct Runner {
  virtual int run() = 0;
};

struct ConcreteRunner: public Runner {
  std::string _arg;
  void setArguments(std::string arg) {_arg=arg;}
  virtual int run() {clog << "ConcreteRunner is called with argument" << _arg << endl;}
};
Run Code Online (Sandbox Code Playgroud)

此方法在 RunAll 部分之外处理参数解析,因此使其尽可能快。