C++调用python完成表达式计算

2026-04-01 11:03:10

1、vc下新建工程,添加代码:

// ExpCalcTest.cpp : Defines the entry point for the console application.

  //

  #include "stdafx.h"

  #include "stdio.h"

  #include "Python.h"

  int main(int argc, char* argv[])

  {

  char exp[][100] = {"1+3*4-6/2","2*(2+3-1)-(7+12)/3","adf + 30", "100/0 + 10"};

  PyObject* pModule = NULL;

  PyObject* pCppEval = NULL;

  PyObject* pArg = NULL;

  PyObject* pResult = NULL;

  int nRet = 0;

  Py_Initialize();

  if (!Py_IsInitialized())

  {

  printf("初始化python环境出错\n");

  return -1;

  }

  pModule = PyImport_ImportModule("cppevalpy");

  if(!pModule)

  {

  printf("导入脚本文件cppevalpy.py出错\n");

  return -1;

  }

  pCppEval = PyObject_GetAttrString(pModule, "cppeval");

  if(!pCppEval)

  {

  printf("获得函数cppeval出错\n");

  return -1;

  }

  char* sResult = (char*) www.gzlij.com malloc(100);

  for(int i=0;i<sizeof(exp)/100*sizeof(char);++i)

  {

  pArg = Py_BuildValue("(s)", exp[i]);

  if(!pArg)

  {

  printf("构造参数出错\n");

  return -1;

  }

  pResult = PyEval_CallObject(pCppEval,pArg);

  PyArg_ParseTuple(pResult,"is",&nRet,&sResult);

  printf("%d,%s\n",nRet,sResult);

  }

  free(sResult);

  Py_Finalize();

  return 0;

  }

2、然后需要修改vc的查找目录:

  include目录添加{python安装目录}/include

  lib目录添加{python安装目录}/libs

  因为我的python安装版没有debug版的lib,所以vc工程我选择release版本。

  如果需要使用debug版,请到网上下载debug版的lib库,或者自己编译python。

  然后在编译生成的可执行程序目录添加脚本文件cppevalpy.py:

3、from __future__ import division

  def cppeval(exp):

  try:

  result = eval(exp)

  except Exception, e:

  return (-1,str(e))

  if isinstance(result,float):

  result = round(result,2)

  result = str(result)

  if result.endswith('.0'):

  result = str(int(float(result)))

  return (1,result)

相关推荐
  • 阅读量:66
  • 阅读量:171
  • 阅读量:95
  • 阅读量:51
  • 阅读量:32
  • 猜你喜欢