python - 在 c++ 中嵌入 python ,示例
问题描述
我很想把这个 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 标头链接到您的程序,但作为更简单的解决方案,我会触发system()
C++ 的命令并处理输出。
这是这个问题的一个例子:
#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。
推荐阅读
- visual-studio-code - 将 vscode snap 包重新安装到新的“code” snap
- angular-universal - 'ng add @nguniversal/express-engine' 不工作
- python - pandas.DataFrame.shift() 填充值不起作用
- ruby - 如何在我的库中对 Net::HTTP 调用进行 rspec 模拟?
- mongodb - 如何在 mongodb 中使用两个条件进行更新
- hadoop - 将输入文件从本地复制到 HDFS 的权限被拒绝
- javascript - JQuery - 向输入添加值,但一个输入没有“.value”属性
- git - 我不想检查一个特定的分支,即使是偶然
- c# - 如何将大量数据中的内容从 sql 对齐到 web?
- spring-boot - 零对一(可选的一对一)实体关系问题(尝试分配空的一对一属性)