阅读教程

C++之python函数调用

[日期:2008-06-06] 来源:  作者:志伟

C++的python函数调用教程,欢迎在线学习最新最全的C++教程。

代码如下,分别演示直接执行python语句、无返回无参数函数调用、返回单参数函数调用。返回多参数函数调用:



#include <Python.h>
#include <iostream>
using namespace std;

//执行python命令
void ExecPythonCommand()
{
 //直接执行
 PyRun_SimpleString("from time import time,ctime\n"
  "print 'Today is',ctime(time())\n");
}

//调用无参数函数
void InvokeNoParm()
{
 PyObject* pMod = NULL;
 PyObject* pFunc = NULL;
 //导入模块
 pMod = PyImport_ImportModule("Life");
 if(pMod)
 {
  //获取函数地址
  pFunc = PyObject_GetAttrString(pMod, "a");
  if(pFunc)
  {
   //函数调用
   PyEval_CallObject(pFunc, NULL);
  }
  else
  {
   cout << "cannot find function a" << endl;
  }
 }
 else
 {
  cout << "cannot find Life.py" << endl;
 }
}

//调用一参数函数
void InvokeWith1Parm()
{
 PyObject* pMod = NULL;
 PyObject* pFunc = NULL;
 PyObject* pParm = NULL;
 PyObject* pRetVal = NULL;
 int   iRetVal = 0;
 //导入模块
 pMod = PyImport_ImportModule("FuncDef");
 if(pMod)
 {
  pFunc = PyObject_GetAttrString(pMod, "square");
  if(pFunc)
  {
   //创建参数
   pParm = Py_BuildValue("(i)", 5);
   //函数调用
   pRetVal = PyEval_CallObject(pFunc, pParm);
   //解析返回值
   PyArg_Parse(pRetVal, "i", &iRetVal);
   cout << "square 5 is: " << iRetVal << endl;
  }
  else
  {
   cout << "cannot find function square" << endl;
  }
 }
 else
 {
  cout << "cannot find FuncDef.py" << endl;
 }
}

//调用多参数函数
void InvokeWith2Parm()
{
 PyObject* pMod = NULL;
 PyObject* pFunc = NULL;
 PyObject* pParm = NULL;
 PyObject* pRetVal = NULL;
 int   iRetVal = 0;
 //导入模块
 pMod = PyImport_ImportModule("add");
 if(pMod)
 {
  pFunc = PyObject_GetAttrString(pMod, "add");
  if(pFunc)
  {
   //创建两个参数
   pParm = PyTuple_New(2);
   //为参数赋值
   PyTuple_SetItem(pParm, 0, Py_BuildValue("i",2000));
   PyTuple_SetItem(pParm, 1, Py_BuildValue("i",3000));
   //函数调用
   pRetVal = PyEval_CallObject(pFunc, pParm);
   //解析返回值
   PyArg_Parse(pRetVal, "i", &iRetVal);
   cout << "2000 + 3000 = " << iRetVal << endl;
  }
  else
  {
   cout << "cannot find function square" << endl;
  }
 }
 else
 {
  cout << "cannot find add.py" << endl;
 }
}

int main(int argc, char* argv[])
{
 Py_Initialize(); //python 解释器的初始化
 
 ExecPythonCommand();
 InvokeNoParm();
 InvokeWith1Parm();
 InvokeWith2Parm();

 Py_Finalize();  // 垃圾回收、清除导入库
 return 0;
}


习惯C++的内存分配释放,突然间不用释放,感觉很蹊跷,上网查发现也没有释放函数。如果真这样的话,是很可怕的,因为无法自己管理内存,但是我相信编译器作者的垃圾回收机制,所以OK,不管!!


InvokePython.rar源码下载



      
      使用百度搜索:C++之python函数调用百度中搜索:C++之python函数调用
阅读:
录入:志伟

评论 】 【 推荐 】 【 打印
上一篇:
下一篇:C++与C#进程通信案例[附源码]
本文评论       全部评论
发表评论


点评: 字数
姓名:

 
搜一下


 
本周热门教程
 

关于我们 | 广告合作 | 法律声明 | 联系站长 | 网站地图 | 网站搜索 | | Top ↑
Copyright © 志伟教程资料网 Powered by zhiweinet 1.0
 本栏目提供:C++之python函数调用