简体   繁体   English

Python 的 C++ 扩展模块返回一个 Numpy 数组

[英]C++ extension module for Python returning a Numpy array

I am trying to create an extension module for Python in C++ using SWIG, which can return a Numpy array to Python.我正在尝试使用 SWIG 在 C++ 中为 Python 创建一个扩展模块,它可以将 Numpy 数组返回给 Python。 This numpy array is multidimensional and each cell can have a value or a list of values(int 64, [int32, int32] etc]. I am able to return a normal array to Python from C++. Could anyone guide me how to proceed with this? I come across numpy.i, arrayinterface , typemaps and I am not quite sure how to begin with. Could someone please guide me in this regard? Thank you.这个 numpy 数组是多维的,每个单元格都可以有一个值或一个值列表(int 64、[int32、int32] 等]。我可以从 C++ 返回一个普通数组到 Python。谁能指导我如何继续这个?我遇到了 numpy.i、 arrayinterface 、typemaps,我不太确定如何开始。有人可以在这方面指导我吗?谢谢。

I think the Numpy C API is a good approach.我认为 Numpy C API 是一个很好的方法。 You can still use SWIG.您仍然可以使用 SWIG。 But I would advice strongly against using SWIG typemaps, they are very complicated.但我强烈建议不要使用 SWIG 类型映射,它们非常复杂。 Instead you can accept and return Numpy arrays as PyObject* pointer in your SWIG'ed signature and build/extract them using the C API.相反,您可以在 SWIG 签名中接受并返回 Numpy 数组作为 PyObject* 指针,并使用 C API 构建/提取它们。 SWIG will wrap this correctly. SWIG 将正确包装它。

If this is your first Python extension, make sure you read the Python C API intro .如果这是您的第一个 Python 扩展,请务必阅读Python C API 介绍 At the very least, you need to know the API contract for reference counting.至少,您需要了解用于引用计数的 API 契约。

Another option would be to implement the buffer protocol API which is understood by numpy.另一种选择是实现 numpy 理解的缓冲区协议API。

Yet another option is Boost.Python if you don't like C code into a C++ world.如果您不喜欢 C 代码进入 C++ 世界,那么另一个选择是Boost.Python I don't have experience with it.我没有这方面的经验。 Personally I like the Python C API for its low complexity.我个人喜欢 Python C API,因为它的复杂性很低。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM