基于raspberry-pi的c++嵌入式python

2024-04-24 15:40:20 发布

您现在位置:Python中文网/ 问答频道 /正文

在我问如何用python调用c++之前,这对我来说相当困难。后来我发现用c++调用python似乎要容易得多。当我遵循the tutorial on codeproject时,我在编译它时遇到了以下问题。在

"pi@raspberrypi ~/New $ g++ led.cpp"

led.cpp:3:20: fatal error: Python.h: No such file or directory
compilation terminated.

我整天都在寻找解决办法。我尝试了sudo apt-get install python-dev(甚至其他版本,如2.7、3.2等等),但是所有的东西都已经完全安装好了,仍然会出现错误。我可以通过我的raspberry pi的find函数找到Python.h的位置。在

最后我在某个网站上找到了以下解决方案:

^{pr2}$

h致命错误被消除,然后出现以下错误。在

/tmp/ccSIJpeH.o: In function `main':
led.cpp:(.text+0x30): undefined reference to `Py_Initialize'
led.cpp:(.text+0x44): undefined reference to `PyString_FromString'
led.cpp:(.text+0x54): undefined reference to `PyImport_Import'
led.cpp:(.text+0x64): undefined reference to `PyModule_GetDict'
led.cpp:(.text+0x84): undefined reference to `PyDict_GetItemString'
led.cpp:(.text+0x94): undefined reference to `PyCallable_Check'
led.cpp:(.text+0xbc): undefined reference to `PyObject_CallObject'
led.cpp:(.text+0xc4): undefined reference to `PyErr_Print'
led.cpp:(.text+0x158): undefined reference to `Py_Finalize'
collect2: ld returned 1 exit status

请告诉我怎么解决这个问题!在

附录:谢谢您回答我的问题。我现在可以编译它了。编译后,它创建了一个“a.out”文件,但当我运行它时它什么也没做。。。在

这是发光二极管.cpp在

// python functions from C code
// 
#include <Python.h>

int main(int argc, char *argv[])
{
    PyObject *pName, *pModule, *pDict, *pFunc, *pValue;

    if (argc < 3) 
    {
        printf("Usage: exe_name python_source function_name\n");
        return 1;
    }

    // Initialize the Python Interpreter
    Py_Initialize();

    // Build the name object
    pName = PyString_FromString(argv[1]);

    // Load the module object
    pModule = PyImport_Import(pName);

    // pDict is a borrowed reference 
    pDict = PyModule_GetDict(pModule);

    // pFunc is also a borrowed reference 
    pFunc = PyDict_GetItemString(pDict, argv[2]);

    if (PyCallable_Check(pFunc)) 
    {
        PyObject_CallObject(pFunc, NULL);
    } else 
    {
        PyErr_Print();
    }

    // Clean up
    Py_DECREF(pModule);
    Py_DECREF(pName);

    // Finish the Python Interpreter
    Py_Finalize();

    return 0;
}

这是我要调用的python代码。py发光二极管在

import RPi.GPIO as GPIO
import time

def ledopen():
    GPIO.setmode(GPIO.BCM)
    GPIO.setup(17, GPIO.OUT)
    GPIO.setup(27, GPIO.OUT)
    GPIO.setup(22, GPIO.OUT)
    GPIO.setup(18, GPIO.OUT)
    GPIO.setup(23, GPIO.OUT)
    GPIO.setup(24, GPIO.OUT)

    GPIO.output(27, True)
    GPIO.output(22, True)
    GPIO.output(18, True)
    GPIO.output(23, True)
    GPIO.output(24, True)
    GPIO.output(17, True)

    time.sleep(5)

    GPIO.output(27, False)
    GPIO.output(22, False)
    GPIO.output(18, False)
    GPIO.output(23, False)
    GPIO.output(24, False)
    GPIO.output(17, False)

    GPIO.cleanup()
    return
ledopen()

我通过输入“sudo./a.out led ledopen”来调用程序。却什么也没做。在


Tags: thetotextpyfalsetrueoutputled