首页 > 解决方案 > 如何从 C++ 中的 Python 脚本中获取变量的值?

问题描述

所以我的问题是我有一个 Python 脚本,它从传感器读取数据,最后我希望这些数据进入 C++ 代码中的字符串。

我试过安装 boost.python 但没有用。(它自己的安装失败了,所以我正在寻找一个新的选项)

基本上问题是:

我有一个这样的脚本:

def sum():
    string = "whateverdata"     // the data got read in
    return string

sum()

我想这样使用它:


#include <string>

int main()
{
   string data = ???        // idk how 

  // processing the string  

   return 0;
}

标签: pythonc++raspberry-pi3

解决方案


我不认为你能做到这一点。至少,我从未亲眼见过。

我会看看你是否可以全部在 python 中或全部在 c++ 中执行此操作。

如果没有,请尝试使用 pyinstaller 将您的 python 文件捆绑到一个 exe 中,然后从 c++ 对 python 脚本进行系统调用。它看起来像:

system("/path/to/pythonexe arg1 arg2");

要将信息输入 c++,您可以让 python 脚本不断地将其写入文本文件,然后 c++ 程序可以读取相同的文本文件。

或者,您可以让 python 脚本将传感器数据打印到标准输出,然后将其读入 c++ 中的缓冲区。有关更多详细信息,请参阅此实现

如果您有任何问题,请告诉我,祝您好运!


推荐阅读