Python 扩展 - 性能

发布于 2024-09-12 01:44:14 字数 401 浏览 1 评论 0原文

我正在使用 Boost.Python 来扩展 python 程序功能。 Python 脚本对本机模块进行了大量调用,因此我非常关心 python 到 cpp 类型转换和数据封送的性能。

我决定尝试通过 Python C API 本地公开方法。也许有人以前已经尝试过?至少在理论上有成功吗?

我遇到的问题是如何将 PyObject* 转换回类实例,PyArg_parse 提供了 O&选项,但我正在寻找的只是一个指向内存中 C++ 对象的指针...我如何在函数中获取它?

<代码> if ( PyArg_ParseTuple(args, "O", &pyTestClass ) ) { // 如何从 pyTestClass 获取 TestClass ? } 谢谢

I am using Boost.Python to extend python program functionality. Python scripts do a lot of calls to native modules so I am really concerned about the performance of python-to-cpp type conversion and data marshaling.

I decided to try exposing methods natively through Python C API. May be somebody already tried that before ? Any success ... at least in theory ?

The problem I run into is that how to convert PyObject* back to class instance, PyArg_parse provides O& option, but what I am looking is simply a pointer to C++ object in memory... how can I get it in function ?


if ( PyArg_ParseTuple(args, "O", &pyTestClass ) )
{
// how to get TestClass from pyTestClass ??
}

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

篱下浅笙歌 2024-09-19 01:44:14

我还没有尝试过 Boost.Python,但我使用原始 C 以及 Cython 扩展了 Python。我推荐 Cython;如果您足够小心,您可以获得与原始 C 具有相同效率的代码,但样板代码要少得多。

至于效率,这是相对的。这取决于您想做什么以及如何做。例如,我经常做的事情是用 C 语言编写一些图像处理或矩阵运算的内部循环,并让 Python 使用指向矩阵的指针作为参数来调用该函数。矩阵本身不会被复制,因此开销很小。

I haven't tried Boost.Python, but I've extended Python using raw C as well as Cython. I recommend Cython; if you're careful enough you can get code with the same efficiency as raw C but with a lot less boilerplate code.

Regarding efficiency, it's relative. It depends on what you want to do and how you do it. For example, what I've done very often is write the inner loop of some image processing or matrix operation in C, and have this function be called by Python with pointers to matrices as arguments. The matrices themselves don't get copied, so the overhead is minimal.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文