cpp调用python

python

1 头文件:#include <Python.h>

2 编译坑:

3 函数说明:示例

/**g++ -o callpy callpy.cpp -I/usr/include/python2.6 -L/usr/lib64/python2.6/config -lpython2.6**/
#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,*pModule,*pDict,*pFunc,*pArgs;

  // 载入名为pytest的脚本
  pName = PyString_FromString("pytest");
  pModule = PyImport_Import(pName);
  if ( !pModule ) { return -1; }
  pDict = PyModule_GetDict(pModule);
  if ( !pDict ) { return -1; }

  // 找出函数名为add的函数
  pFunc = PyDict_GetItemString(pDict, "add");

  // 参数进栈
  PyObject *pArgs;
  pArgs = PyTuple_New(2);

  PyTuple_SetItem(pArgs, 0, Py_BuildValue("l",3));
  PyTuple_SetItem(pArgs, 1, Py_BuildValue("l",4));

  // 调用Python函数
  PyObject_CallObject(pFunc, pArgs);

  Py_DECREF(pName);
  Py_DECREF(pArgs);
  Py_DECREF(pModule);

  // 关闭Python
  Py_Finalize();
  return 0;
}

以上是 cpp调用python 的全部内容, 来源链接: utcz.com/z/387993.html

回到顶部