首先有三个部分,
1.python代码,名为pyadd.py,代码如下:
def add(a=1,b=1):print "*************"print "in python function add"print "a="+str(a)print "b="+str(b)print "ret="+str(a+b)return a+b
2.C调用代码,名为calladd.c,代码如下:
#include <stdio.h>#include <stdlib.h>#include <Python.h>int PyCall(const char * module,const char * function,const char * format,...){PyObject * pModule=NULL;PyObject * pFunc = NULL;PyObject * pRet = NULL;PyObject * pArgs = NULL;PyRun_SimpleString("import sys");PyRun_SimpleString("sys.path.append('./')");if(!(pModule=PyImport_ImportModule(module))){printf("error:1");return -1;}if(!(pFunc = PyObject_GetAttrString(pModule,function))){printf("error:2");return -2;}va_list vargs;va_start(vargs,format);pArgs=Py_VaBuildValue(format,vargs);va_end(vargs);pRet=PyEval_CallObject(pFunc,pArgs);int ret ;PyArg_Parse(pRet,"i",&ret);return ret;}int main(int argc,char ** agrv){printf("This is main\n");Py_Initialize();printf("(in main )ret=%d\n",PyCall("pyadd","add","()"));printf("(in main)ret=%d\n",PyCall("pyadd","add","(i)",10));printf("(in main)ret=%d\n",PyCall("pyadd","add","(ii)",20,20));Py_Finalize();return 0;}
3.Makefile,代码如下:
add:gcc -I/usr/include/python2.4/ -L/usr/lib/ -lpython2.4 -o add lean:rm -rf *.o add
在linux平台,当python及C 语言环境安装完成后,可参考(/3/c-api/index.html)理解C代码中函数用法。
简单说明一下执行过程,
1.在shell下执行:make #需要在Makefile的当前目录下执行
2.执行新生成的add ,即可显示add结果
执行结果如下:
This is main
*************
in python function add
a=1
b=1
ret=2
(in main )ret=2
*************
in python function add
a=10
b=1
ret=11
(in main)ret=11
*************
in python function add
a=20
b=20
ret=40
(in main)ret=40
如果觉得《linux平台下C语言调用python代码示例》对你有帮助,请点赞、收藏,并留下你的观点哦!