C調用Python函數相關代碼示例剖析
作者:佚名
C調用Python函數的相關操作將會在這篇文章中通過一段代碼示例來為大家詳細介紹。初學者們可以通過這里介紹的內容充分掌握這一應用技巧。
我們在使用C語言的時候,有時會遇到需要調用Python函數來完成一些特定的功能。那么接下來,我們將會在這里為大家詳細介紹一下C調用Python函數的相關操作方法,希望可以給大家帶來一些幫助。
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調用Python函數的代碼示例:
- #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系統前,必須使用Py_Initialize對其
- //進行初始化。它會載入Python的內建模塊并添加系統路
- //徑到模塊搜索路徑中。這個函數沒有返回值,檢查系統
- //是否初始化成功需要使用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;
- }
- // 找出函數名為add的函數
- pFunc = PyDict_GetItemString(pDict, "add");
- if ( !pFunc || !PyCallable_Check(pFunc) )
- {
- printf("can't find function [add]");
- getchar();
- return -1;
- }
- // 參數進棧
- 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函數
- 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;
- }
以上就是我們對C調用Python函數的相關操作方法的介紹。
【編輯推薦】
責任編輯:曹凱
來源:
博客園