C++調用Python(詳細教程步驟)

C++調用Python詳細教程,一步步實現,減少坑,以及實現過程中遇到的坑的解決方法。

環境

  • Qt5.13 msvc2017 64
  • Python3.7 64

配置

將Python安裝目錄下的include libs拷貝到Qt工程目錄下

.pro配置

win32:CONFIG(release, debug|release): LIBS += -L$$PWD/libs/ -lpython37
else:win32:CONFIG(debug, debug|release): LIBS += -L$$PWD/libs/ -lpython37d
INCLUDEPATH += $$PWD/include
DEPENDPATH += $$PWD/include

添加頭文件

#define PY_SSIZE_T_CLEAN
#include <Python.h>

第一行代碼

//初始化Python環境
​
Py_Initialize();

發現出錯:error: expected unqualified-id before ';' token PyType_Slot slots; /

 

修改object.h

typedef struct{
​
  const char* name;
​
  int basicsize;
​
  int itemsize;
​
  unsigned int flags;
​
  \#undef slots  
​
  PyType_Slot *slots; /* terminated by slot==0. */
​
  \#define slots Q_SLOTS
​
} PyType_Spec;

 

再次編譯通過(注意:編譯模式debug/release,使用debug模式需要在安裝python是勾選上debug)

或者要想使用debug模式,修改pyconfig.h中

將python37_d.lib 改爲python37.lib

#ifdef MS_COREDLL
\#    if !defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_BUILTIN)
•        /* not building the core - must be an ext */
\#        if defined(_MSC_VER)
•            /* So MSVC users need not specify the .lib
•            file in their Makefile (other compilers are
•             generally taken care of by distutils.) */
\#            if defined(_DEBUG)
\#                pragma comment(lib,"python37.lib")/*pragma comment(lib,"python37_d.lib")*/
\#            elif defined(Py_LIMITED_API)
\#                pragma comment(lib,"python3.lib")
\#            else
\#                pragma comment(lib,"python37.lib")
\#            endif /* _DEBUG */
\#        endif /* _MSC_VER */
\#    endif /* Py_BUILD_CORE */
\#endif /* MS_COREDLL */

同時註釋掉

#ifdef _DEBUG
//#    define Py_DEBUG //註釋掉
\#endif

最後將test.py扔到.exe目錄下,或者設置一下環境能讓exe找到

或者將執行的python文件添加到執行路徑

//PyRun_SimpleString 執行python語句
PyRun_SimpleString("import sys");
PyRun_SimpleString("sys.path.append('../../CleanAssess/')");
PyRun_SimpleString("sys.path.append('../../CleanAssess/images/')");

其他具體怎麼調用python,自行百度,通用方法。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章