首页 > 解决方案 > 在 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;
}

任何人都可以帮我做到这一点!?提前致谢 。

标签: pythonc++

解决方案


对于这样的简单应用程序,我不会将 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。


推荐阅读