一、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
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! "); 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! "); 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! "); 38 return -1; 39 } 40 41 pFunc = PyDict_GetItemString(pDict,"add"); 42 if(!pFunc || !PyCallable_Check(pFunc)) 43 { 44 printf("Can't find function! "); 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 }
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)
二、Python调用C
1.新建一个pcallc.c
1 #include <stdio.h> 2 #include <pcallc.h> 3 4 int add(int a,int b) 5 { 6 int c= 0; 7 c = a+b; 8 printf("add c:",c); 9 return c; 10 }
2.新建一个pcallc.h
1 #ifndef PCALLC_H 2 #define PCALLC_H 3 4 int add(); 5 6 #endif
3.生成动态库:pcallc.so
gcc -o pcallc.so -shared -fPIC pcallc.c
4.新建pcallc.py
1 #-*- coding:utf-8 -*- 2 3 import ctypes 4 5 loadso = ctypes.cdll.LoadLibrary 6 lib= loadso("./pcallc.so") 7 lib.add(1,2) 8 9 print("***finish***")
5.运行pcallc.py
python pcallc.py
add c:3
finish!