c++調用Python首先安裝Python,以win7為例,Python路徑為:c:/Python35/,通過mingw編譯c++代碼。
編寫makefile文件,首先要添加包含路徑:
inc_path += c:/Python35/include
然后添加鏈接參數:
ld_flag += c:/Python35/libs/libpython35.a
在源文件中添加頭文件引用:
#include "Python.h"
Python解釋器需要進行初始化,完成任務后需要終止:
void start(){ int r=Py_IsInitialized(); //1為已經初始化了 if (r==0) { //Py_SetPythonHome(L"C://Python35"); Py_Initialize(); //初始化 p_main_Module =PyImport_ImportModule("__main__"); if (!p_main_Module) { throw ""; } }}void end(){ Py_Finalize(); //清理}
程序部署時可以將c:/Python35/lib目錄復制到執行程序路徑下,或者通過Py_SetPythonHome(L"C://Python35");設置Python的安裝目錄。
C++調用Python的基本需求:
1、運行Python指令
PyRun_SimpleString("print(os.getcwd(),a)");pyext.eval(R"(a+='qwer')");
2、加載Python模塊
PyObject * pModule =PyImport_ImportModule("tp"); //test:Python文件名,若腳本有錯則返回空PyRun_SimpleString("import os");
3、給Python的變量賦值
對于數值,使用Py_BuildValue:
Py_BuildValue("") NonePy_BuildValue("i", 123) 123Py_BuildValue("iii", 123, 456, 789) (123, 456, 789)Py_BuildValue("s", "hello") 'hello'Py_BuildValue("ss", "hello", "world") ('hello', 'world')Py_BuildValue("s#", "hello", 4) 'hell'Py_BuildValue("()") ()Py_BuildValue("(i)", 123) (123,) Py_BuildValue("(ii)", 123, 456) (123, 456)Py_BuildValue("(i,i)", 123, 456) (123, 456)Py_BuildValue("[i,i]", 123, 456) [123, 456]Py_BuildValue("{s:i,s:i}", "abc", 123, "def", 456) {'abc': 123, 'def': 456}
對于其他數據結構,使用相應的函數設置,例如:
PyObject *pArgs = PyTuple_New(1);PyObject *pDict = PyDict_New(); //創建字典類型變量 PyDict_SetItemString(pDict, "Name", Py_BuildValue("s", "WangYao")); //往字典類型變量中填充數據 PyDict_SetItemString(pDict, "Age", Py_BuildValue("i", 25)); //往字典類型變量中填充數據 PyTuple_SetItem(pArgs, 0, pDict);//0---序號 將字典類型變量添加到參數元組中
構造好對象以后,通過PyObject_SetAttrString來設置進入Python中:
PyObject *ps=PyUnicode_DecodeUTF8(val,strlen(val),"ignore"); //構造了一個對象PyObject_SetAttrString(p_main_Module,key,ps); //設置
4、獲取Python變量的值
首先取得變量的指針,然后通過PyArg_Parse解析
pModule =PyImport_ImportModule("__main__");pReturn = PyObject_GetAttrString(pModule, "a"); //可以獲得全局變量int size = PyDict_Size(pReturn); PyObject *pNewAge = PyDict_GetItemString(pReturn, "Age"); int newAge;PyArg_Parse(pNewAge, "i", &newAge);
對于元組的解析:
int ok;ok = PyArg_ParseTuple(args, "s", &s); //Python call: f('whoops!')ok = PyArg_ParseTuple(args, "lls", &k, &l, &s);//Python call: f(1, 2,'three')ok = PyArg_ParseTuple(args, "(ii)s#", &i, &j, &s, &size);//Python call: f((1, 2), 'three')ok = PyArg_ParseTuple(args, "s|si", &file, &mode, &bufsize);//Python calls://f('spam')//f('spam', 'w')//f('spam', 'wb', 100000)
5、調用Python函數
PyObject * pfun=PyObject_GetAttrString(pModule, "testdict"); //testdict:Python文件中的函數名PyObject *pReturn = PyEval_CallObject(pfun, pArgs); //調用函數
6、設置函數讓Python調用
首先定義c函數,然后聲明方法列表,然后聲明模塊,然后增加這個模塊,最后調用
static int numargs=1890;static PyObject* emb_numargs(PyObject *self, PyObject *args) //C函數{ if(!PyArg_ParseTuple(args, ":numargs")) return NULL; return PyLong_FromLong(numargs);}static PyMethodDef EmbMethods[] = { //方法列表 {"numargs", emb_numargs, METH_VARARGS, "Return the number of arguments received by the process."}, {NULL, NULL, 0, NULL}};static PyModuleDef EmbModule = { //模塊聲明 PyModuleDef_HEAD_INIT, "emb", NULL, -1, EmbMethods, NULL, NULL, NULL, NULL};static PyObject* PyInit_emb(void) //模塊初始化函數{ return PyModule_Create(&EmbModule);}//增加模塊:PyImport_AppendInittab("emb", &PyInit_emb); //增加一個模塊
Python部分代碼:
import embprint("Number of arguments", emb.numargs())
以上所述是小編給大家介紹的C++調用Python基礎功能實例詳解,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對VEVB武林網網站的支持!
新聞熱點
疑難解答