簡體   English   中英

在示例中將python嵌入c ++

[英]embedding python in c++ , example

我很想將這個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標頭鏈接到您的程序,但是作為更簡單的解決方案,我將觸發C ++的system()命令並處理輸出。

這里是這個問題的一個例子:

#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。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM