python与c语言交互—学习012
1.C语言是结构化编程语言,Python是面向对象的语言,Python调用C语言,没有问题。但是,反过来则不行,不许C调用Python。
使用Python/C API中的PyImport_Import()函数可以在C程序中导入Python模块。
分析:先引用模块(PyImport_ImportModule),
然后获取模块中的函数(PyObject_GetAttrString),
对c传入python 的参数做类型转换(Py_BuildValue(“(s)”,”hello_python”)),
最后直接调用函数并传递参数(PyEval_CallObject)。
#include "/usr/include/python2.5/Python.h"
#include <stdio.h>
int main(int arg,char **argv){
PyObject *modelname,*model,*dict,*func,*args;
char *name="os";//模块名
//初始化Python
Py_Initialize();
if (!Py_IsInitialized()){
printf("初始化失败\n");
return -1;
}
//直接运行Python语句
PyRun_SimpleString("print '初始化成功'");
//导入Python模块
modelname=PyString_FromString(name);
model=PyImport_Import(modelname);
if (model){
printf("Load model ok\n");
}
else{
printf("Model %s not found!\n",name);
return -1;
}
dict=PyModule_GetDict(model);
if(!dict){
printf("获取字典失败\n");
return -1;
}
else{
printf("获取字典成功\n");
}
//从模块中找到“System”函数
func=PyDict_GetItemString(dict,"system");
if(!func || !PyCallable_Check(func)){
printf("函数无效\n");
return -1;
}
args=PyTuple_New(1);
PyTuple_SetItem(args,0,Py_BuildValue("s","ls"));//l=long,s=string...
//调用函数
PyObject_CallObject(func,args);
Py_DECREF(modelname);
Py_DECREF(model);
Py_DECREF(func);
Py_DECREF(args);
Py_DECREF(dict);
//垃圾回收
Py_Finalize();
return 0;
}
————————————————————————我是分割线——————————————————-
call.py
def test():
print ‘hello world‘ def add(a,b):
return a + b
print ‘hello world‘ def add(a,b):
return a + b
api.py
import io
def load_test():
fp = open('call.py','r')
buffer = ''
if fp:
buffer = fp.read()
fp.close()
return buffer
cpp代码:
#include <stdio.h>
#include <stdlib.h>
#include <Python.h> int main(int argc, char *argv[])
{
Py_Initialize();
if(!Py_IsInitialized())
{
return –1;
}
PyRun_SimpleString(“import sys“);
PyRun_SimpleString(“sys.path.append(‘./’)“);
PyObject* pName;
PyObject* pModule;
PyObject* pDict;
PyObject* pFunc;
pName = PyString_FromString(“api“);
pModule = PyImport_Import(pName);
if(!pModule)
{
printf(“can’t find call.py“);
getchar();
return –1;
}
pDict = PyModule_GetDict(pModule);
if(!pDict)
{
return –1;
}
{
pFunc = PyDict_GetItemString(pDict,“load_test“);
if(!pFunc || !PyCallable_Check(pFunc))
{
printf(“can’t find function [test]“);
getchar();
return –1;
}
PyObject *pFn = PyObject_CallObject(pFunc,0);
char* buffer = PyString_AsString(pFn);
printf(“%s\n“,buffer);
PyObject* o = Py_CompileString(buffer,“none“,Py_file_input);
PyObject* m = PyImport_ExecCodeModule(“a.a“,o);
PyObject* d = PyModule_GetDict(m);
pFunc = PyDict_GetItemString(d,“add“);
if(!pFunc || !PyCallable_Check(pFunc))
{
printf(“can’t find function [add]“);
getchar();
return –1;
}
PyObject* args = PyTuple_New(2);
PyTuple_SetItem(args,0,Py_BuildValue(“l“,3));
PyTuple_SetItem(args,1,Py_BuildValue(“l“,4));
PyObject *pAdded = PyObject_CallObject(pFunc,args);
int ret = PyInt_AsLong(pAdded);
printf(“add value:%d\n“,ret);
}
Py_Finalize();
system(“PAUSE“);
return 0;
}
#include <stdlib.h>
#include <Python.h> int main(int argc, char *argv[])
{
Py_Initialize();
if(!Py_IsInitialized())
{
return –1;
}
PyRun_SimpleString(“import sys“);
PyRun_SimpleString(“sys.path.append(‘./’)“);
PyObject* pName;
PyObject* pModule;
PyObject* pDict;
PyObject* pFunc;
pName = PyString_FromString(“api“);
pModule = PyImport_Import(pName);
if(!pModule)
{
printf(“can’t find call.py“);
getchar();
return –1;
}
pDict = PyModule_GetDict(pModule);
if(!pDict)
{
return –1;
}
{
pFunc = PyDict_GetItemString(pDict,“load_test“);
if(!pFunc || !PyCallable_Check(pFunc))
{
printf(“can’t find function [test]“);
getchar();
return –1;
}
PyObject *pFn = PyObject_CallObject(pFunc,0);
char* buffer = PyString_AsString(pFn);
printf(“%s\n“,buffer);
PyObject* o = Py_CompileString(buffer,“none“,Py_file_input);
PyObject* m = PyImport_ExecCodeModule(“a.a“,o);
PyObject* d = PyModule_GetDict(m);
pFunc = PyDict_GetItemString(d,“add“);
if(!pFunc || !PyCallable_Check(pFunc))
{
printf(“can’t find function [add]“);
getchar();
return –1;
}
PyObject* args = PyTuple_New(2);
PyTuple_SetItem(args,0,Py_BuildValue(“l“,3));
PyTuple_SetItem(args,1,Py_BuildValue(“l“,4));
PyObject *pAdded = PyObject_CallObject(pFunc,args);
int ret = PyInt_AsLong(pAdded);
printf(“add value:%d\n“,ret);
}
Py_Finalize();
system(“PAUSE“);
return 0;
}
这段代码和上一篇有点区别
主要区别是从从内存载入python模块然后调用函数
主要部分是这块:
PyObject* o = Py_CompileString(buffer,"none",Py_file_input);
PyObject* m = PyImport_ExecCodeModule("a.a",o);
PyObject* d = PyModule_GetDict(m);
buffer是python源码字符串
在python2.7中执行正常
编译:
gcc -o ./python_c_function ./python_c_function.c -I/usr/include/python2.6 -L/usr/lib/python2.6 -lpython
[root@localhost c_python]# ./python_c_function
def test():
print 'hello world'
def add(a,b):
return a + b
add value:7
转载自:https://blog.csdn.net/shenwansangz/article/details/44019433