简体   繁体   中英

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. 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.

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. (It is not necessary to use Cython; Python extensions can be written by hand. But it will make the task significantly easier.)

@ramtha Z28 with the limited information you provided... do you have access to the C++ code itself or are you calling a DLL? You can wrap a function in Cython easily to communicate between Python and C++ if you have the source code. Wrap all the C++ blocks in cpdef statements which are accessible from Python and C++. 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

If it is a DLL you have to declare all the constants, functions, return values. Actually this example may be something like what you're using already: 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. For real-time applications, UDP protocol is a preferable choice.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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