[英]Embedded python in c++ on raspberry pi
在我問如何在python中調用c ++之前,但這對我來說很難。 后來我發現,如果在c ++中調用python似乎要容易得多。 在我遵循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等。),但一切都已經完全安裝,仍然出現錯誤。 我可以通過樹莓派的find函數找到Python.h的位置。
最終我在某個站點上找到了以下解決方案:
pi@raspberrypi ~/New $ g++ $(python-config --includes) led.cpp
消除了Python.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
請告訴我如何解決這個問題!
附錄 :謝謝Nitori回答我的問題。 我現在可以編譯它。 編譯后,它創建了一個“ a.out”文件,但是當我運行它時,它什么也沒做...
這是led.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代碼。 led.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 led ledopen”來調用該程序。 它什么也沒做。
您還需要針對Python進行鏈接。 對於您的編譯方式,它應該可以正常工作: g++ $(python-config --includes --libs) led.cpp
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.