C調(diào)用Python函數(shù)相關(guān)代碼示例剖析
作者:佚名
C調(diào)用Python函數(shù)的相關(guān)操作將會(huì)在這篇文章中通過(guò)一段代碼示例來(lái)為大家詳細(xì)介紹。初學(xué)者們可以通過(guò)這里介紹的內(nèi)容充分掌握這一應(yīng)用技巧。
我們?cè)谑褂肅語(yǔ)言的時(shí)候,有時(shí)會(huì)遇到需要調(diào)用Python函數(shù)來(lái)完成一些特定的功能。那么接下來(lái),我們將會(huì)在這里為大家詳細(xì)介紹一下C調(diào)用Python函數(shù)的相關(guān)操作方法,希望可以給大家?guī)?lá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對(duì)其
- //進(jìn)行初始化。它會(huì)載入Python的內(nèi)建模塊并添加系統(tǒng)路
- //徑到模塊搜索路徑中。這個(gè)函數(shù)沒(méi)有返回值,檢查系統(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ù)進(jìn)棧
- pArgs = PyTuple_New(2);
- // PyObject* Py_BuildValue(char *format, ...)
- // 把C++的變量轉(zhuǎn)換成一個(gè)Python對(duì)象。當(dāng)需要從
- // C++傳遞變量到Python時(shí),就會(huì)使用這個(gè)函數(shù)。此函數(shù)
- // 有點(diǎn)類似C的printf,但格式不同。常用的格式有
- // s 表示字符串,
- // i 表示整型變量,
- // f 表示浮點(diǎn)數(shù),
- // O 表示一個(gè)Python對(duì)象。
- 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);
- // 關(guān)閉Python
- Py_Finalize();
- return 0;
- }
- //一下為個(gè)人實(shí)踐的另一套方法
- #include < Python.h>
- #include < conio.h>
- int main()
- {
- Py_Initialize();
- if (!Py_IsInitialized())
- {
- printf("初始化錯(cuò)誤\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;
- }
以上就是我們對(duì)C調(diào)用Python函數(shù)的相關(guān)操作方法的介紹。
【編輯推薦】
責(zé)任編輯:曹凱
來(lái)源:
博客園