【问题标题】:Python to C++ function conversion using Boost.Python使用 Boost.Python 将 Python 转换为 C++ 函数
【发布时间】:2010-10-15 20:54:53
【问题描述】:

我有一堆用 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 元信息中提取所有必需的数据以通用方式执行此操作 - 在编译时我不应该知道我将调用哪些函数以及它们接受哪些参数。

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

让我知道你的想法。

谢谢

【问题讨论】:

  • 你真的需要检查AddFunction()中的所有类型吗?仅将方法和参数存储在某处并在RunAll() 中调用这些方法还不够吗?这样,当您执行这些方法时,您会遇到任何与类型相关的错误,而 Boost.Python 会为您完成。
  • 嗯,不。基本上这个想法是最小化这些函数调用之间的时间间隔,因此必须在此之前检查所有参数。 RuAll 应该只知道 C++ 函数指针(即函子),还有其他建议吗?
  • 在那种情况下我没有。 :-) 我不认为这是 Boost.Python 设计的用例,你将很难改变它来做你想做的事。在调用您的方法之间花费在 Python 中的时间真的很重要,以至于您必须这样做吗?但我猜你已经完成了你的分析...... :-)
  • 好吧,我有一些建议......我会尝试查看经常调用的方法组合,并将这些组合变成它们自己的方法。

标签: c++ python boost-python


【解决方案1】:

我会考虑在 python 级别缓存函数及其参数 - 使用教程的Keyword arguments 部分中的最新形式保存参数,然后稍后调用您的 C++ 函数unpacking saved arguments 在 python 级别完成解包将使您免受任何提升类型安全的复杂性(所有类型检查都将在 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;}
};

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-04
    • 2018-01-07
    • 1970-01-01
    • 2020-12-09
    • 2019-03-26
    • 1970-01-01
    • 1970-01-01
    • 2021-12-12
    相关资源
    最近更新 更多