博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Python返回参数给C++
阅读量:3962 次
发布时间:2019-05-24

本文共 2142 字,大约阅读时间需要 7 分钟。

Python嵌入C++,C++如何获取Python的参数

本文参考于用C或C++扩展Python

1.应用场景:

当我们使用编程借用Python计算,将计算结果返回给C++的时候,我们可以使用此方法将Python参数返回给C++

2.函数原理:

PyArg_ParseTuple()函数声明如下:

int PyArg_ParseTuple(PyObject *arg, const char *format, ...);

所述ARG参数必须是包含在Python传递给C函数的参数列表的元组对象。该格式参数必须是一个格式字符串,其语法中解释解析参数和建设值在Python / C API参考手册。其余参数必须是其类型由格式字符串确定的变量的地址。

请注意,在PyArg_ParseTuple()检查Python参数是否具有必需的类型时,它无法检查传递给调用的C变量的地址的有效性:如果在那里出错,则代码可能会崩溃或至少覆盖内存中的随机位。所以要小心!

注意,提供给调用者的任何Python对象引用都是 借用的引用。不要减少其参考计数!

3.使用方法

#define PY_SSIZE_T_CLEAN  /* Make "s#" use Py_ssize_t rather than int. */#include 
int 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) */}

4.具体实例

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/

你可能感兴趣的文章
安装 docker-compose (实测可用,妈妈再也不用担心被墙了)
查看>>
docker下删除none的images
查看>>
Linux提权获取敏感信息方法
查看>>
Ubuntu 16.04开机A start job is running for Raise network interface(5min 4s)解决方法
查看>>
Ubuntu 16.04开机隐藏菜单缩短时间
查看>>
Ubuntu 更换国内源
查看>>
Ubuntu16.04下Docker pull connection refused 解决办法
查看>>
postgres基本操作(个人总结版)
查看>>
The AnimationClip 'Walk' used by the Animation component 'Pig' must be marked as Legacy.
查看>>
《Linux内核设计与实现》- Linux的进程
查看>>
inet_ntoa()
查看>>
POSIX消息队列mq_open问题
查看>>
两个数组a[N],b[N],其中A[N]的各个元素值已知,现给b[i]赋值,b[i] = a[0]*a[1]*a[2]…*a[N-1]/a[i];
查看>>
用户态切换到内核态的3种方式
查看>>
笔试常见的智力题(附答案)
查看>>
内核库函数
查看>>
Linux 系统内核空间与用户空间通信的实现与分析
查看>>
如何写好应用型学术论文
查看>>
如何查看进程的各种限制
查看>>
64位int类型用printf输出问题
查看>>