Tensorflow模型移植Arm之一:C如何调用Python

1.新建一个Python文件,名称为py_multipy.py:

1 #import numpy as np
2 def multiply(a=1,b=2):
3     print('Function of python called!')
4     print('a:',a)
5     print('b:',b)
6     print('a*b:',a*b)
7     #print('numpy a*b:',np.multiply(a,b))
8     
View Code

2.新建一个C调用文件,名称为call_python.c

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #include <Python.h>
 4 
 5 int main()
 6 {
 7     Py_Initialize();
 8     
 9     if(!Py_IsInitialized())
10     {
11         printf("Python init failed!\n");
12         return -1;
13     }
14     
15 
16     PyRun_SimpleString("import sys");
17     PyRun_SimpleString("sys.path.append('./')");
18        
19     PyObject *pDict = NULL;
20     PyObject *pModule = NULL;
21     PyObject *pName = NULL;
22     PyObject *pFunc = NULL;
23     PyObject *pArgs = NULL;
24     
25     pName = PyString_FromString("py_add");
26     pModule = PyImport_Import(pName);
27     if (!pModule)
28     {
29         printf("Load py_add.py failed!\n");
30         getchar();
31         return -1;
32     }
33     
34     pDict = PyModule_GetDict(pModule);
35     if(!pDict)
36     {
37         printf("Can't find dict in py_add!\n");
38         return -1;
39     }
40     
41     pFunc = PyDict_GetItemString(pDict,"add");
42     if(!pFunc || !PyCallable_Check(pFunc))
43     {
44         printf("Can't find function!\n");
45         getchar();
46         return -1;
47     }
48     
49     pArgs = PyTuple_New(2);
50     
51     PyTuple_SetItem(pArgs,0,Py_BuildValue("i",111));
52     PyTuple_SetItem(pArgs,1,Py_BuildValue("i",222));
53     
54     PyObject_CallObject(pFunc,pArgs);
55     
56     if(pName)
57     {
58         Py_DECREF(pName);
59     }
60     
61     if(pArgs)
62     {
63         Py_DECREF(pArgs);
64     }
65     
66     if(pModule)
67     {
68         Py_DECREF(pModule);
69     }
70     
71     Py_Finalize();
72     return 0;
73 
74     
75 }
View Code

3.编译C文件

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

在当前目录下生成可执行文件call_python

4.执行新生成的文件:./call_python

显示结果如下:

        Function of python called!

        ('a:',111)

        ('b:',222)

        ('a*b:',333)

猜你喜欢

转载自www.cnblogs.com/jimchen1218/p/11752356.html