c++ - 使用 Boost.Python 将 Python 转换为 C++ 函数

标签 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
}

基本上,我试图将所有功能归结为我程序的 native 部分。 问题是我不确定是否可以从 Boost 元信息中提取所有必需的数据以通用方式执行此操作 - 在编译时我不应该知道我要调用什么函数以及它们接受什么参数。

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

让我知道你的想法。

谢谢

最佳答案

我会考虑在 python 级别缓存函数及其参数 - 使用来自 Keyword arguments 的最新形式保存参数教程的一部分,稍后调用您的 C++ 函数 unpacking saved arguments在 python 级别完成的解包将使您免受任何增强类型安全并发症的影响(所有类型检查都将在 RunAll 阶段完成,使其速度更慢且安全性更低)。

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

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 部分之外处理参数解析,因此使其尽可能快。

关于c++ - 使用 Boost.Python 将 Python 转换为 C++ 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3946055/

相关文章:

c++ - 对 `TextOutA@20' 的 undefined reference

c++ - 扩展 CCSprite

c++ - {x} 和 '= {x}' 初始化之间有什么区别(如果有)?

c++ - 代码块中的 SDL_ShowSimpleMessageBox 令人困惑的错误、内存不足和 undefined reference

jquery - 使用 json 在 python/django 中设置用户登录并且不知道从哪里开始

python - Keras 自定义数据生成器 - 错误 : 'int' object has no attribute 'shape'

python - 更改值时Opencv重绘图像

c++ - 向 Python 公开一个类并在 Python 中也对其进行更改

python-3.x - Boost Python 示例失败两次

python - 如何让 bjam 检测我在 Windows 上安装的 Python?