python - Linux C調用Python 函數

1.Python腳本,名稱爲py_add.pypython

1 def add(a=1,b=1):
2     print('Function of python called!')
3     print('a = ',a)
4     print('b = ',b)
5     print('a + b = ',a+b)

2.C代碼app

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #include <Python.h>
 4 
 5 int main(int argc,char **argv){
 6     //初始化,載入python的擴展模塊
 7     Py_Initialize();
 8     //判斷初始化是否成功
 9     if(!Py_IsInitialized()){
10             printf("Python init failed!\n");
11             return -1;
12         }
13     //PyRun_SimpleString 爲宏,執行一段python代碼
14     //導入當前路徑
15     PyRun_SimpleString("import sys");
16     PyRun_SimpleString("sys.path.append('./')");
17 
18     PyObject *pName = NULL;
19     PyObject *pModule = NULL;
20     PyObject *pDict = NULL;
21     PyObject *pFunc = NULL;
22     PyObject *pArgs = NULL;
23 
24     //加載名爲py_add的python腳本
25     pName = PyString_FromString("py_add");
26     pModule = PyImport_Import(pName);
27     if(!pModule){
28             printf("Load py_add.py failed!\n");
29             getchar();
30             return -1;
31         }
32     pDict = PyModule_GetDict(pModule);
33     if(!pDict){
34             printf("Can't find dict in py_add!\n");
35             return -1;
36         }
37     pFunc = PyDict_GetItemString(pDict,"add");
38     if(!pFunc || !PyCallable_Check(pFunc)){
39             printf("Can't find function!\n");
40             getchar();
41             return -1;
42         }
43     /*
44     向Python傳參數是以元組(tuple)的方式傳過去的,
45     所以咱們實際上就是構造一個合適的Python元組就
46     能夠了,要用到PyTuple_New,Py_BuildValue,PyTuple_SetItem等幾個函數
47     */
48     pArgs = PyTuple_New(2);
49     //  PyObject* Py_BuildValue(char *format, ...) 
50     //  把C++的變量轉換成一個Python對象。當須要從 
51     //  C++傳遞變量到Python時,就會使用這個函數。此函數 
52     //  有點相似C的printf,但格式不一樣。經常使用的格式有 
53     //  s 表示字符串, 
54     //  i 表示整型變量, 如Py_BuildValue("ii",123,456)
55     //  f 表示浮點數, 
56     //  O 表示一個Python對象
57     PyTuple_SetItem(pArgs,0,Py_BuildValue("i",123));
58     PyTuple_SetItem(pArgs,1,Py_BuildValue("i",321));
59     //調用python的add函數
60     PyObject_CallObject(pFunc,pArgs);
61     //清理python對象
62     if(pName){
63         Py_DECREF(pName);
64         }
65     if(pArgs){
66         Py_DECREF(pArgs);
67         }
68     if(pModule){
69         Py_DECREF(pModule);
70         }
71     //關閉python調用
72     Py_Finalize();
73     return 0;
74 }

3,編譯函數

gcc -I/usr/include/python2.7/  mian.c -o main -L/usr/lib/ -lpython2.7

備註:連接Python的庫需在最後,不然可能會出現如下的錯誤提示:ui

undefined reference to 'Py_Initialize'

4,運行結果spa

相關文章
相關標籤/搜索