简体   繁体   English

如何将变量值从C ++传递给Python?

[英]How to pass variable value from C++ to Python?

I have a sensor value which can be read using the C++ only because it was implemented using it , I want to pass location value (two float variable) of one sensor to Python. 我有一个只能使用C ++读取的传感器值,因为它是使用C ++实现的,因此我想将一个传感器的位置值(两个float变量)传递给Python。 I have been reading a lot and I found shared memory , piping and more any idea what is the best way to do it ? 我读了很多书,发现共享内存,管道和更多的主意是什么是最好的方法?

It's not clear from your question whether this is a standalone C++ program or a library. 从您的问题还不清楚这是一个独立的C ++程序还是一个库。

If it's a standalone program, use the subprocess module to invoke it and read its output. 如果它是一个独立程序,请使用子进程模块来调用它并读取其输出。

If it's a library, use Cython to construct a Python extension module that wraps the library. 如果是库,请使用Cython构造包装该库的Python扩展模块。 (It is not necessary to use Cython; Python extensions can be written by hand. But it will make the task significantly easier.) (没有必要使用Cython; 可以手动编写Python扩展。但是,它将大大简化任务。)

@ramtha Z28 with the limited information you provided... do you have access to the C++ code itself or are you calling a DLL? @ramtha Z28,其中包含您提供的有限信息...您是否有权访问C ++代码本身或正在调用DLL? You can wrap a function in Cython easily to communicate between Python and C++ if you have the source code. 如果您有源代码,则可以轻松地在Cython中包装一个函数以在Python和C ++之间进行通信。 Wrap all the C++ blocks in cpdef statements which are accessible from Python and C++. 将所有C ++块包装在cpdef语句中,可以从Python和C ++访问cpdef语句。 Example files are here which show you how to include a C program in Cython and interact with Python: https://github.com/cythonbook/examples/tree/master/07-wrapping-c/01-wrapping-c-functions-mt-random 此处的示例文件向您展示了如何在Cython中包含C程序以及如何与Python交互: https : //github.com/cythonbook/examples/tree/master/07-wrapping-c/01-wrapping-c-functions- MT-随机

If it is a DLL you have to declare all the constants, functions, return values. 如果是DLL,则必须声明所有常量,函数和返回值。 Actually this example may be something like what you're using already: http://people.seas.harvard.edu/~krussell/html-tutorial/wrap_dll.html 实际上,此示例可能类似于您正在使用的示例: http : //people.seas.harvard.edu/~krussell/html-tutorial/wrap_dll.html

I'm not familiar with python however, a simple approach is to use some communication protocols such as serial ports or udp which is a network protocol. 我不熟悉python,但是一种简单的方法是使用一些通信协议,例如串行端口或网络协议udp。 For real-time applications, UDP protocol is a preferable choice. 对于实时应用程序,UDP协议是首选。

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

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