我很想将这个 python 程序嵌入到 c++ 中,但我在那里有点挣扎,我从来没有研究过 python,甚至在阅读了其他网站上关于该方法的解释后我也做不到没有真正应用它,因为我不知道那些python成员是什么,我想在c++下运行这个程序,这段代码很好,但在c++版本中找不到,这就是我决定的原因使用嵌入式选项。
这是python程序
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Le Raspbery Pi envoie des messages à l'Arduino
import serial # bibliothèque permettant la communication série
import time # pour le délai d'attente entre les messages
ser = serial.Serial('/dev/ttyACM0', 9600)
compteur = 0
while True: # boucle répétée jusqu'à l'interruption du programme
if compteur < 6:
compteur = compteur + 1
else:
compteur = 0
ser.write(str(compteur))
time.sleep(1) # on attend pendant 2 secondes
这是我试过的嵌入式程序,但我很确定它是错误的,因为没有调用 python 对象
#include <iostream>
#include <Python.h>
int main(int argc, char **argv) {
Py_Initialize();
return 0;
}
谁能帮我做这个!?提前致谢。
最佳答案
对于像这样的简单应用程序,我不会将 python header 链接到您的程序,但作为更简单的解决方案,我会触发 C++ 的 system()
命令并处理输出。
这是来自 this 的示例问题:
#include <cstdio>
#include <iostream>
#include <memory>
#include <stdexcept>
#include <string>
#include <array>
std::string exec() {
std::array<char, 128> buffer;
std::string result;
const char* cmd = "./python script.py";
std::shared_ptr<FILE> pipe(popen(cmd, "r"), pclose);
if (!pipe) throw std::runtime_error("popen() failed!");
while (!feof(pipe.get())) {
if (fgets(buffer.data(), 128, pipe.get()) != nullptr)
result += buffer.data();
}
return result;
}
然后您必须更改 python 代码中的无限循环,以便 python 程序终止并执行其余的 C++ 代码,然后您可以使用 C++ 程序中的 python 脚本探测 arduino。
关于python - 在 c++ 中嵌入 python,示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50997744/