python与c语言交互---学习012
2015-03-02 16:02
295 查看
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)。
call.py
def test():
print 'hello world'
def add(a,b):
return a + b
api.py
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;
}
这段代码和上一篇有点区别
主要区别是从从内存载入python模块然后调用函数
主要部分是这块:
buffer是python源码字符串
在python2.7中执行正常
编译:
使用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
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;
}
这段代码和上一篇有点区别
主要区别是从从内存载入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
相关文章推荐
- Python学习4-Python的交互
- c语言write与python的struct模块交互
- Lua学习笔记——C语言与Lua的交互
- Python_3_学习之路_(1)变量_用户交互_if_else___while__for
- Python_3_学习之路_(1)变量_用户交互_if_else___while__for
- python与c++交互学习入门之5
- Python学习笔记012——装饰器
- python学习笔记--Django入门三 Django 与数据库的交互:数据建模
- Python学习-用户交互raw_input()
- python学习1--ftp交互
- c语言write与python的struct模块交互
- 9.17学习笔记 java和python交互,java8位UUID,mac闪电接口高清线导购
- python与c++交互学习入门之5
- python学习笔记10(用户交互程序)
- 使用Python学习selenium测试工具-5:元素交互
- 列表:一个打了激素的数组3 - 零基础入门学习Python012
- python学习012
- C语言学习012:将代码文件分成多个文件
- IPython(jupyter)简单介绍和基本交互操作 - 千月的python linux 系统管理指南学习笔记(5)
- python学习笔记9.1-系统交互接口