c语言调用Python脚本-2 - Cpper - C++博客
c语言调用Python脚本-2
python代码二段:
call.py
deftest():
print'hello world'
defadd(a,b):
returna+b
api.py
importio
defload_test():
fp=open('call.py','r')
buffer=''
iffp:
buffer=fp.read()
fp.close()
returnbuffer
cpp代码:
#include<stdio.h>
#include<stdlib.h>
#include<Python.h>
intmain(intargc,charargv[])
{
Py_Initialize();
if(!Py_IsInitialized())
{
return-1;
}
PyRun_SimpleString("import sys");
PyRun_SimpleString("sys.path.append('./')");
PyObjectpName;
PyObjectpModule;
PyObjectpDict;
PyObjectpFunc;
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;
}
PyObjectpFn=PyObject_CallObject(pFunc,0);
charbuffer=PyString_AsString(pFn);
printf("%s\n",buffer);
PyObjecto=Py_CompileString(buffer,"none",Py_file_input);
PyObjectm=PyImport_ExecCodeModule("a.a",o);
PyObjectd=PyModule_GetDict(m);
pFunc=PyDict_GetItemString(d,"add");
if(!pFunc||!PyCallable_Check(pFunc))
{
printf("can't find function [add]");
getchar();
return-1;
}
PyObjectargs=PyTuple_New(2);
PyTuple_SetItem(args,0,Py_BuildValue("l",3));
PyTuple_SetItem(args,1,Py_BuildValue("l",4));
PyObjectpAdded=PyObject_CallObject(pFunc,args);
intret=PyInt_AsLong(pAdded);
printf("add value:%d\n",ret);
}
Py_Finalize();
system("PAUSE");
return0;
}
这段代码和上一篇有点区别
主要区别是从从内存载入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中执行正常原文链接: https://www.cnblogs.com/lexus/archive/2013/01/24/2875680.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/76674
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!