您好,登錄后才能下訂單哦!
本篇文章為大家展示了C語言程序怎么調(diào)用Python函數(shù),內(nèi)容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細介紹希望你能有所收獲。
Python腳本,存為pytest.py
def add(a,b): print "in python function add" print "a = " + str(a) print "b = " + str(b) print "ret = " + str(a+b) return a + b
C調(diào)用Python函數(shù)的代碼示例:
#include < stdio.h> #include < stdlib.h> #include "C:/Python26/include/python.h" #pragma comment(lib, "C:\\Python26\\libs\\python26.lib") int main(int argc, char** argv) { // 初始化Python //在使用Python系統(tǒng)前,必須使用Py_Initialize對其 //進行初始化。它會載入Python的內(nèi)建模塊并添加系統(tǒng)路 //徑到模塊搜索路徑中。這個函數(shù)沒有返回值,檢查系統(tǒng) //是否初始化成功需要使用Py_IsInitialized。 PyObject *pName, *pModule, *pDict, *pFunc, *pArgs, *pRetVal; Py_Initialize(); // 檢查初始化是否成功 if ( !Py_IsInitialized() ) { return -1; } // 載入名為pytest的腳本(注意:不是pytest.py) pName = PyString_FromString("pytest"); pModule = PyImport_Import(pName); if ( !pModule ) { printf("can't find pytest.py"); getchar(); return -1; } pDict = PyModule_GetDict(pModule); if ( !pDict ) { return -1; } // 找出函數(shù)名為add的函數(shù) pFunc = PyDict_GetItemString(pDict, "add"); if ( !pFunc || !PyCallable_Check(pFunc) ) { printf("can't find function [add]"); getchar(); return -1; } // 參數(shù)進棧 pArgs = PyTuple_New(2); // PyObject* Py_BuildValue(char *format, ...) // 把C++的變量轉(zhuǎn)換成一個Python對象。當需要從 // C++傳遞變量到Python時,就會使用這個函數(shù)。此函數(shù) // 有點類似C的printf,但格式不同。常用的格式有 // s 表示字符串, // i 表示整型變量, // f 表示浮點數(shù), // O 表示一個Python對象。 PyTuple_SetItem(pArgs, 0, Py_BuildValue("l",3)); PyTuple_SetItem(pArgs, 1, Py_BuildValue("l",4)); // 調(diào)用Python函數(shù) pRetVal = PyObject_CallObject(pFunc, pArgs); printf("function return value : %ld\r\n", PyInt_AsLong(pRetVal)); Py_DECREF(pName); Py_DECREF(pArgs); Py_DECREF(pModule); Py_DECREF(pRetVal); // 關閉Python Py_Finalize(); return 0; } //一下為個人實踐的另一套方法 #include < Python.h> #include < conio.h> int main() { Py_Initialize(); if (!Py_IsInitialized()) { printf("初始化錯誤\n"); return -1; } PyObject* pModule = NULL; PyObject* pFunc = NULL; PyObject* pArg = NULL; PyObject* pRetVal = NULL; pModule = PyImport_ImportModule("hello"); pFunc = PyObject_GetAttrString(pModule,"hello"); pArg = Py_BuildValue("(i,i)",33,44); pRetVal = PyObject_CallObject(pFunc,pArg); printf("%d\n",PyInt_AsLong(pRetVal)); Py_Finalize(); _getch(); return 0; }
上述內(nèi)容就是C語言程序怎么調(diào)用Python函數(shù),你們學到知識或技能了嗎?如果還想學到更多技能或者豐富自己的知識儲備,歡迎關注億速云行業(yè)資訊頻道。
免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。