简体   繁体   English

C ++和Python之间的数据传输

[英]Data transfer between C++ and Python

I would like to share memory between C++ and Python. 我想在C ++和Python之间共享内存。

My problem: 我的问题:

  1. I am working with big data sets (up to 6 GB of RAM) in C++. 我正在使用C ++中的大数据集(最多6 GB的RAM)。 All calculations are done in c++. 所有计算都是用c ++完成的。
  2. Then, I want to "paste" all my results to a Python program. 然后,我想将所有结果“粘贴”到Python程序中。 But I can only write my data on disk, and then read that file from Python, which is not efficient. 但我只能在磁盘上写入我的数据,然后从Python中读取该文件,这是无效的。

Is there any way to "map" memory corresponding to C++ variables so that I may access the data from Python? 有没有办法“映射”对应于C ++变量的内存,以便我可以从Python访问数据? I don't want to copy 6GB of data onto a hard drive. 我不想将6GB的数据复制到硬盘上。

First path : I think the more appropriate way for you to go is ctypes . 第一条道路 :我认为更合适的方式是ctypes You can create a shared library, and then load the functions of the shared library in Python, and fill all the data containers you want in Python. 您可以创建一个共享库,然后在Python中加载共享库的功能,并在Python中填充所需的所有数据容器。

In Windows, you can create a DLL, and in Linux you can create a shared .so library. 在Windows中,您可以创建DLL,在Linux中,您可以创建共享的.so库。

Now this has the advantage that this will be independent of your Python version. 现在,这有一个优势,即它将独立于您的Python版本。

Second path : I think it's less appropriate but you can get it to work, which is the Python C Extension . 第二条路径 :我认为它不太合适,但你可以让它工作,这是Python C扩展 With this, you can call Python data containers ( PyObject s) and fill them inside C. 有了这个,你可以调用Python数据容器( PyObject s)并在C里面填充它们。

However, the code you compile here will always need to be linked to Python libraries. 但是,您在此处编译的代码将始终需要链接到Python库。

Which one to use? 哪一个使用? :

  • Use ctypes if you have some functions you want to call in C/C++, and then do the rest of the work in Python. 如果您想要在C / C ++中调用某些函数,请使用ctypes,然后在Python中完成其余的工作。
  • Use Python C Extension if you have some functions you want to call in Python, and you want to do the rest in C/C++. 如果您想要在Python中调用某些函数,请使用Python C Extension,并且您希望在C / C ++中完成其余的工作。

With both options, you can transfer huge blocks of memory between C++ and Python without necessarily involving any disk read/write operations. 使用这两个选项,您可以在C ++和Python之间传输大量内存,而不必涉及任何磁盘读/写操作。

Hope this helps. 希望这可以帮助。

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

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