C ++和Python之间的通信 [英] Communication between C++ and Python

查看:171
本文介绍了C ++和Python之间的通信的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种高效且智能的方式在C ++程序和Python脚本之间发送数据。我有一个C ++程序,可以实时计算30Hz的一些坐标。我想用Python脚本访问这些坐标。我的第一个想法是简单地创建一个.txt文件并向其写入坐标,然后让Python打开该文件并进行读取。但是我认为使用RAM而不是硬盘驱动器必须是一种更智能,更高效的方法。

I am looking for an efficient and smart way to send data between a C++-program and a Python-script. I have a C++ program which calculates some coordinates in-real-time 30Hz. And I wanna access these coordinates with a Python-script. My first idea was to simply create a .txt-file and write the coordinates to it, and then have Python open the file and read. But I figured that it must be a smarter and more efficient way using the RAM and not the harddrive.

有人对此有好的解决方案吗? C ++程序应将3坐标(x,y,z)写入某种缓冲区或文件,Python程序可以将其打开并读取它们。理想情况下,C ++程序每次都会重写坐标,并且同时读取和写入文件/缓冲区没有问题。

Does anyone have any good solutions for this? The C++ program should write 3coordinates (x,y,z) to some sort of buffer or file, and the Python program can open it and read them. Ideally the C++-program overwrites the coordinates every time and there's no problem with reading and writing to the file/buffer at the same time.

感谢您的帮助

推荐答案

您有两个基本选择:


  • 在两个单独的进程中,将C ++代码和python代码作为两个单独的程序运行,并使用 IPC机制

  • 按照grc的建议将C ++代码链接到您的代码。

如果您已经编写了完整的复杂C ++程序,则第一个选项可能会更好。另外,通常更容易调试和维护。

The first option is probably better if you already have a complete complex C++ program written. Also, it's generally easier to debug and maintain.

对于特定的IPC机制,套接字是常用的,因为它们在操作系统级别具有某种标准化的跨平台API,如果您需要两个程序在不同的计算机上运行,​​则仍然可以使用。如果要使用现代台式机,套接字应该足以每秒传输30次三个坐标。

As for a specific IPC mechanism, sockets are commonly used because they have somewhat standardized cross-platform APIs at the OS level, and still work if you need the two programs running on different machines. Sockets should be more than enough for transferring three coordinates 30 times each second, if you're dealing with a modern desktop machine.

如果确实需要更高的性能,则可以查看(命名或命名)管道,但您可能需要在C ++方面进行一些额外的工作才能使其跨平台。

If you really need more performance, you could look into (named or named) pipes, but you'll probably need some extra work on the C++ side to make it cross-platform.

这篇关于C ++和Python之间的通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆