Python嵌入C實(shí)例的相關(guān)具體解析
Python在實(shí)際的相關(guān)應(yīng)用中就有很強(qiáng)大功能,以及C在實(shí)際的運(yùn)行中也具有很強(qiáng)的功能。如果對Python嵌入C你有過此想法的話,你就可以瀏覽我們的文章,其中包括中Python嵌入C的實(shí)例。望你會有所收獲。
在VC++ 6.0中新建一個名為“EmbPython”的空“Win32 Console Application”工程。向其添加如下所示的“EmbPython.c”文件。
- #include <stdio.h>
- #include <Python.h>
- int main(int argc, char* argv[])
- {
- PyObject *modulename, *module, *dic, *func, *args, *rel, *list;
- char *funcname1 = "sum";
- char *funcname2 = "strsplit";
- int i;
- Py_ssize_t s;
printf("-==在C中嵌入Python==-\n");/* Python解釋器的初始化*/
- Py_Initialize();
- if(!Py_IsInitialized())
- {
- printf("初始化失敗!");
- return -1;
- }
/* 導(dǎo)入Python模塊,并檢驗(yàn)是否正確導(dǎo)入 */
- modulename = Py_BuildValue("s", "pytest");
- module = PyImport_Import(modulename);
- if(!module)
- {
- printf("導(dǎo)入pytest失敗!");
- return -1;
- }
/* 獲得模塊中函數(shù)并檢驗(yàn)其有效性 */
- dic = PyModule_GetDict(module);
- if(!dic)
- {
- printf("錯誤!\n");
- return -1;
- }
/* 獲得sum函數(shù)地址并驗(yàn)證 */
- func = PyDict_GetItemString(dic,funcname1);
- if(!PyCallable_Check(func))
- {
printf("不能找到函數(shù) %s",funcname1);
- return -1;
- }
/* 構(gòu)建列表 */
- list = PyList_New(5);
printf("使用Python中的sum函數(shù)求解下列數(shù)之和\n");
- for (i = 0; i < 5; i++)
- {
- printf("%d\t",i);
- PyList_SetItem(list,i,Py_BuildValue("i",i));
- }
- printf("\n");
/* 構(gòu)建sum函數(shù)的參數(shù)元組*/
以上就是對把Python嵌入C中的實(shí)例相關(guān)的內(nèi)容的介紹,望你會有所收獲。
【編輯推薦】