準備工作
新建一個控制檯應用,寫個簡單的Hello World程序。
環境配置
C++調用Python腳本需要用到Python安裝目錄下的include、libs 以及相關的dll,因此需要把相應的路徑添加到工程中。 如果libs文件夾下沒有python36_d.lib
文件,可複製python36.lib
並重命名爲python36_d.lib
備用。
-
添加頭文件目錄以及庫文件目錄
在解決方案資源管理器中選中當前項目,右鍵選擇屬性:
-
在項目屬性頁中的VC++目錄選項裏的包含目錄、庫目錄中分別添加Python的include和libs的路徑:
-
在鏈接器選項下的輸入中添加附加依賴項
python37_d.lib
(位於Python安裝目錄下的libs文件夾中,直接填寫文件名即可)。
[注] Debug 版本的附加依賴項填寫python37_d.lib
,Release 版本的附加依賴項填寫python37.lib
。
代碼測試
-
先寫一個Python的測試腳本,用於打印當前日期和時間:
#!/usr/bin/python #coding:utf-8 import time def run(name): print("Hi,"+name+".") print("It is "+time.strftime("%Y-%m-%d %X", time.localtime())+".") def main(): run("Kevin") if __name__=='__main__': main()
運行腳本得到如下結果
-
C++調用
#include <iostream> #include <Python.h> using namespace std; int main(int argc, char *argv[]) { cout << "Python function called by Cpp!" << endl; // 初始化Python環境 Py_Initialize(); // 判斷初始化是否成功 if (!Py_IsInitialized()) { cout << "Initialize failed ..." << endl; // 關閉 Python 腳本解釋器,釋放內存。 Py_Finalize(); return -1; } PyObject *pModule = NULL; PyObject *pFunc = NULL; PyObject *pArg = NULL; // 添加模塊路徑 PyRun_SimpleString("import sys"); PyRun_SimpleString("sys.path.append('./')"); // 導入模塊 pModule = PyImport_ImportModule("DemoForCpp"); if (!pModule) // 檢查模塊是否導入成功 { cout << "Python file import failed ..." << endl; Py_Finalize(); return -1; } else { // 導入函數 pFunc = PyObject_GetAttrString(pModule, "run"); //python 腳本里的函數名 if (!pFunc) // 檢查函數是否導入成功 { cout << "Function import failed ..." << endl; Py_Finalize(); return -1; } //C++類型轉換爲python類型 PyObject *pParams = Py_BuildValue("(s)", "Michael"); char *result; pArg = PyEval_CallObject(pFunc, pParams); // 調用函數 //獲取結果,python類型轉換爲C++類型。 PyArg_Parse(pArg, "s", &result); cout << result << endl; } Py_Finalize(); return 0; }
-
調用結果