python - Linux C调用Python 函数

1.Python脚本,名称为py_add.py

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代码

 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的库需在最后,否则可能会出现以下的错误提示:

undefined reference to 'Py_Initialize'

4,运行结果

 

posted @ 2018-06-12 15:49  极客先锋  阅读(4958)  评论(0编辑  收藏  举报