本文共 2142 字,大约阅读时间需要 7 分钟。
Python嵌入C++,C++如何获取Python的参数
本文参考于用C或C++扩展Python
当我们使用编程借用Python计算,将计算结果返回给C++的时候,我们可以使用此方法将Python参数返回给C++
PyArg_ParseTuple()函数声明如下:
int PyArg_ParseTuple(PyObject *arg, const char *format, ...);
所述ARG参数必须是包含在Python传递给C函数的参数列表的元组对象。该格式参数必须是一个格式字符串,其语法中解释解析参数和建设值在Python / C API参考手册。其余参数必须是其类型由格式字符串确定的变量的地址。
请注意,在PyArg_ParseTuple()检查Python参数是否具有必需的类型时,它无法检查传递给调用的C变量的地址的有效性:如果在那里出错,则代码可能会崩溃或至少覆盖内存中的随机位。所以要小心!
注意,提供给调用者的任何Python对象引用都是 借用的引用。不要减少其参考计数!
#define PY_SSIZE_T_CLEAN /* Make "s#" use Py_ssize_t rather than int. */#includeint ok;int i, j;long k, l;const char *s;Py_ssize_t size;ok = PyArg_ParseTuple(args, ""); /* No arguments */ /* Python call: f() */ok = PyArg_ParseTuple(args, "s", &s); /* A string */ /* Possible Python call: f('whoops!') */ok = PyArg_ParseTuple(args, "lls", &k, &l, &s); /* Two longs and a string */ /* Possible Python call: f(1, 2, 'three') */ok = PyArg_ParseTuple(args, "(ii)s#", &i, &j, &s, &size); /* A pair of ints and a string, whose size is also returned */ /* Possible Python call: f((1, 2), 'three') */{ const char *file; const char *mode = "r"; int bufsize = 0; ok = PyArg_ParseTuple(args, "s|si", &file, &mode, &bufsize); /* A string, and optionally another string and an integer */ /* Possible Python calls: f('spam') f('spam', 'w') f('spam', 'wb', 100000) */}{ int left, top, right, bottom, h, v; ok = PyArg_ParseTuple(args, "((ii)(ii))(ii)", &left, &top, &right, &bottom, &h, &v); /* A rectangle and a point */ /* Possible Python call: f(((0, 0), (400, 300)), (10, 10)) */}{ Py_complex c; ok = PyArg_ParseTuple(args, "D:myfunction", &c); /* a complex, also providing a function name for errors */ /* Possible Python call: myfunction(1+2j) */}
C++文件接收两个字符串变量,见第四部分参数输入。
const char *myConstant,*myCoefficient; PyArg_ParseTuple(getNum, "ss", &myConstant,&myCoefficient);
python文件将float类型转换为str类型返回
return str(new_theta[0]),str(new_theta[1])
输出结果
qDebug()<
“61.612672451266164,115.05459255617593”
注意:C++接收Python返回的变量必须是两个及以上(只返回一个数时会显示乱码),没有两个你随便添加一个返回数据(比如说自然数1)
转载地址:http://reezi.baihongyu.com/