Cpper
C/C++高级工程师 Android高级软件工程师 IT集成工程师 音频工程师 熟悉c,c++,java,c#,py,js,asp等多种语言 程序猿
先上python代码:
# call.py

def test():
    print 
'hello world'


def add(a,b):
    
return a + b

再上c代码
#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("call");
    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,"test");
        
if(!pFunc || !PyCallable_Check(pFunc))
        {
            printf(
"can't find function [test]");
            getchar();
            
return -1;
        }
        
        PyObject_CallObject(pFunc,
0);
    }
    
    {
        pFunc 
= PyDict_GetItemString(pDict,"add");
        
if(!pFunc || !PyCallable_Check(pFunc))
        {
            printf(
"can't find function [test]");
            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_DECREF(args);
    }    
    
    Py_DECREF(pName);
    Py_DECREF(pDict);
    Py_DECREF(pModule);
    Py_Finalize();    
    system(
"PAUSE");    
    
return 0;
}
就不做解释了
不过如何从字符串中载入模块?
posted on 2013-01-14 21:44 ccsdu2009 阅读(3842) 评论(0)  编辑 收藏 引用 所属分类: Python脚本

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理