Link 使用 Python 脚本的 C++ 程序输出

Link C++ program output with Python script

我有一个 C++ 程序,它使用一些非常具体的方法来计算数据集(30,000 个元素)的成对距离。输出文件将是 20 GB,看起来像这样:

point1, point2, distancex
pointi, pointj, distancexx
.....

然后我将文件输入到 Python 并使用 Python (NumPy) 进行聚类。使用 Python 读取输出文件需要很长时间。有没有办法直接将 C++ 程序与我的 Python 代码连接起来,以节省在中间文件上 I/O 的时间?也许使用 SWIG?

我假设您一直在保存 ascii。你可以修改你的 C++ 代码来编写二进制文件,然后用 numpy.fromfile.

读取它

为了更直接的连接,您可以使用 swig 将 C++ 代码包装为一个库(删除 main() 并从 Python 驱动它)。这允许您在 C++ 和 Python 之间共享数组内存。

您可以通过第二种方法使用 Python 的 buffer protocol on the C++ side together with numpy.frombuffer on the Python side. Or you can use the numpy headers to directly work on numpy arrays in C++. Here is a small swig example project。 (免责声明:我写的。)