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

时间:2010-10-15 20:54:53

标签: 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++

在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
}

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

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

让我知道你的想法。

由于

1 个答案:

答案 0 :(得分:1)

我会考虑在python级别缓存函数及其参数 - 使用教程的Keyword arguments部分中的最新表单保存参数,稍后调用C ++函数unpacking saved arguments在python级别完成解包将隔离你可以从任何类型的安全性并发症(所有类型检查将在RunAll阶段完成,使其更慢,更不安全)。

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

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

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