C++调用Python基础功能实例详解

2020-01-06 17:20:14王旭

4、获取Python变量的值

首先取得变量的指针,然后通过PyArg_Parse解析


pModule =PyImport_ImportModule("__main__");
pReturn = PyObject_GetAttrString(pModule, "a"); //可以获得全局变量
int size = PyDict_Size(pReturn); 
PyObject *pNewAge = PyDict_GetItemString(pReturn, "Age"); 
int newAge;
PyArg_Parse(pNewAge, "i", &newAge); 

对于元组的解析:


int ok;
ok = PyArg_ParseTuple(args, "s", &s); //Python call: f('whoops!')
ok = PyArg_ParseTuple(args, "lls", &k, &l, &s);//Python call: f(1, 2,'three')
ok = PyArg_ParseTuple(args, "(ii)s#", &i, &j, &s, &size);//Python call: f((1, 2), 'three')
ok = PyArg_ParseTuple(args, "s|si", &file, &mode, &bufsize);//Python calls:
//f('spam')
//f('spam', 'w')
//f('spam', 'wb', 100000)

5、调用Python函数


PyObject * pfun=PyObject_GetAttrString(pModule, "testdict"); //testdict:Python文件中的函数名
PyObject *pReturn = PyEval_CallObject(pfun, pArgs); //调用函数

 6、设置函数让Python调用

首先定义c函数,然后声明方法列表,然后声明模块,然后增加这个模块,最后调用


static int numargs=1890;
static PyObject* emb_numargs(PyObject *self, PyObject *args) //C函数
{
  if(!PyArg_ParseTuple(args, ":numargs"))
    return NULL;
  return PyLong_FromLong(numargs);
}
static PyMethodDef EmbMethods[] = { //方法列表
  {"numargs", emb_numargs, METH_VARARGS,
   "Return the number of arguments received by the process."},
  {NULL, NULL, 0, NULL}
};
static PyModuleDef EmbModule = { //模块声明
  PyModuleDef_HEAD_INIT, "emb", NULL, -1, EmbMethods,
  NULL, NULL, NULL, NULL
};
static PyObject* PyInit_emb(void) //模块初始化函数
{
  return PyModule_Create(&EmbModule);
}
//增加模块:
PyImport_AppendInittab("emb", &PyInit_emb); //增加一个模块

Python部分代码:


import emb
print("Number of arguments", emb.numargs())

以上所述是小编给大家介绍的C++调用Python基础功能实例详解,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对ASPKU网站的支持!


注:相关教程知识阅读请移步到C++教程频道。