CWYAlpha

Just another WordPress.com site

Thought this was cool: c语言调用Python脚本-2

leave a comment »


python代码二段:

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中执行正常

ccsdu2009 2013-01-15 21:39 发表评论

from C++博客_Kevin Lynx: http://www.cppblog.com/gaimor/archive/2013/01/15/197300.html

Written by cwyalpha

一月 16, 2013 在 4:54 上午

发表在 Uncategorized

发表评论

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / 更改 )

Twitter picture

You are commenting using your Twitter account. Log Out / 更改 )

Facebook photo

You are commenting using your Facebook account. Log Out / 更改 )

Google+ photo

You are commenting using your Google+ account. Log Out / 更改 )

Connecting to %s

%d 博主赞过: