python - 在 c++ 中嵌入 python,示例

标签 python c++

我很想将这个 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/

相关文章:

javascript - 在没有响应的情况下执行 python 函数 - Django

python - 检查两个数组是否可以在 python 中广播

c++ - 调用虚函数时继承类 "invalid pointer error"

c++ - undeclared identifier 和 identifier is undefined 是什么意思?如何修复错误?

Python - 从导入的文件调用父文件中的函数

python - 在 C : dynamic build of format string? 中读取包含许多变量的 .dat 文件

c++ - 在 C++ 中使用 unicode char 支持从 TCHAR 转换为 char*

c++ - 没有删除运算符的指针类型

c++ - 头文件和附加库

python - 将字符串列表转换为python中的列表