【C++】Python呼叫C/C++互相呼叫(轉)
阿新 • • 發佈:2018-11-04
參考源:
20181025
1.pytest.py
#test function def add(a,b): print " in python function add" print "a = " + str(a) print "b = " + str(b) print "ret = " + str(a+b) return def foo(a): print "in python function foo" print "a = " + str(a) print "ret = " + str(a * a) return class guestlist: def __init__(self): print "aaaa" def p(): print "bbbbb" def __getitem__(self, id): return "ccccc" def update(): guest = guestlist() print guest['aa'] #update()
2.main.cpp
#include <iostream> #include <windows.h> #include <string> #include <stdexcept> #include <vector> #include <algorithm> using namespace std; /**g++ -o callpy callpy.cpp -I/usr/include/python2.6 -L/usr/lib64/python2.6/config -lpython2.6**/ #include <Python.h> int main(int argc, char** argv) { // 初始化Python //在使用Python系統前,必須使用Py_Initialize對其進行初始化。它會載入Python的內建模組並新增系統路徑到模組搜尋路徑中。這個函式沒有返回值,檢查系統是否初始化成功需要使用Py_IsInitialized。 Py_Initialize(); // 檢查初始化是否成功 if (!Py_IsInitialized()) { return -1; } // 添加當前路徑把輸入的字串作為Python程式碼直接執行,返回0表示成功,-1表示有錯。大多時候錯誤都是因為字串中有語法錯誤。 PyRun_SimpleString("import sys"); PyRun_SimpleString("print '---import sys---'"); PyRun_SimpleString("sys.path.append('./')"); PyObject *pName, *pModule, *pDict, *pFunc/*, *pArgs*/; // 載入名為pytest的指令碼 pName = PyBytes_FromString("pytest"); //py3將 PyString_FromString 修改為 PyBytes_FromString pModule = PyImport_Import(pName); if (!pModule) { printf("can't find pytest.py"); getchar(); return -1; } pDict = PyModule_GetDict(pModule); if (!pDict) { return -1; } // 找出函式名為add的函式 printf("----------------------\n"); pFunc = PyDict_GetItemString(pDict, "add"); if (!pFunc || !PyCallable_Check(pFunc)) { printf("can't find function [add]"); getchar(); return -1; } // 引數進棧 PyObject *pArgs; pArgs = PyTuple_New(2); // PyObject* Py_BuildValue(char *format, ...) // 把C++的變數轉換成一個Python物件。當需要從 // C++傳遞變數到Python時,就會使用這個函式。此函式 // 有點類似C的printf,但格式不同。常用的格式有 // s 表示字串, // i 表示整型變數, // f 表示浮點數, // O 表示一個Python物件。 PyTuple_SetItem(pArgs, 0, Py_BuildValue("l", 3)); PyTuple_SetItem(pArgs, 1, Py_BuildValue("l", 4)); // 呼叫Python函式 PyObject_CallObject(pFunc, pArgs); //下面這段是查詢函式foo 並執行foo printf("----------------------\n"); pFunc = PyDict_GetItemString(pDict, "foo"); if (!pFunc || !PyCallable_Check(pFunc)) { printf("can't find function [foo]"); getchar(); return -1; } pArgs = PyTuple_New(1); PyTuple_SetItem(pArgs, 0, Py_BuildValue("l", 2)); PyObject_CallObject(pFunc, pArgs); printf("----------------------\n"); pFunc = PyDict_GetItemString(pDict, "update"); if (!pFunc || !PyCallable_Check(pFunc)) { printf("can't find function [update]"); getchar(); return -1; } pArgs = PyTuple_New(0); PyTuple_SetItem(pArgs, 0, Py_BuildValue("")); PyObject_CallObject(pFunc, pArgs); Py_DECREF(pName); Py_DECREF(pArgs); Py_DECREF(pModule); // 關閉Python Py_Finalize(); system("pause"); return 0; }