如何使用 Boost::Python 在不修改基类的情况下向导出类添加方法?
我有一个无法修改的 C++ 类。然而,该类拥有一个 std::list<> 。我需要能够在 Python 扩展中访问的项目。由于 Boost::Python 似乎没有 std::list 和 Python 列表之间的内置转换,所以我希望能够用 C++ 编写一个方法来为我完成此转换,稍后,当我正在将 C++ 类映射到 Python 类,我可以附加此方法。
我更喜欢如果我可以调用这样的方法
baseClassInstance.get_std_list_of_items_as_python_list()
I have a class in C++ that I can't modify. However, that class holds an std::list<> of items that I need to be able to access in a Python extension. Since Boost::Python doesn't seem to have a built-in conversion between an std::list and a Python list, I was hoping to be able to write a method in C++ that could do this conversion for me and later, when I am mapping the C++ classes to Python classes, I could attach this method.
I would prefer if I could just call the method like
baseClassInstance.get_std_list_of_items_as_python_list()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
要以更通用的方式回答这个问题,您可以将任何具有正确签名的 C++ 函数附加到 class_ 声明中的 python 导出。
假设有一个 foo 类:
您可以定义一个自由函数,它将 foo 的引用作为第一个参数:
并像 foo 的成员一样导出它:
To answer the question in a more general way, you can attach any c++ function that has the right signature to the python export in the class_ declaration.
assume a class foo:
You can define a free function that takes a reference to foo as the first argument:
And export it just like a member of foo:
Boost 提供了一个包装迭代器的帮助器,记录如下: http://www.boost.org/doc/libs/1_42_0/libs/python/doc/v2/iterator.html
该示例听到该页面的结尾对我有用,您只需要明确地创建转换,例如:
为了修改 C++ 类而不更改它,我习惯于创建一个子类化真实类的瘦包装器。这是一个很好的地方来分离所有的琐事,让我的 C++ 对象与 Python 感觉很舒服。
Boost provides a helper to wrap iterators which is documented here: http://www.boost.org/doc/libs/1_42_0/libs/python/doc/v2/iterator.html
The example hear the end of that page worked for me, you just need to explicitly create the conversion, for example:
To modify the C++ class without changing it, I am in the habit of creating a thin wrapper that subclasses the real class. This makes a nice place to separate out all the crud that makes my C++ objects feel comfortable from Python.