gpt4 book ai didi

Python C 接口(interface) PyArg_ParseTuple 失败

转载 作者:行者123 更新时间:2023-11-30 17:59:24 24 4
gpt4 key购买 nike

我有一个用 C 编写的 Python 模块,其中公开了许多函数。其中之一的 Python 定义为:

def SetPowerSupply(voltage, current, supply):

其中电压 = 浮点,电流 = 浮点,电源 = int。在 C 端,我有这个:

float voltage, current;
int supply;

if (!PyArg_ParseTuple(args, "ffi", &voltage, &current, &supply))
{
// Failed to parse
// ...
}

我的一个脚本编写者有一个脚本,其中该函数无法解析参数,提示需要一个整数。据我所知,实际上正在传入一个整数,因为如果在错误分支中我这样做:

PyObject *num = PyNumber_Float(PyTuple_GetItem(args, 0));
voltage = PyFloat_AsDouble(num);
Py_XDECREF(num);

num = PyNumber_Float(PyTuple_GetItem(args, 1));
current = PyFloat_AsDouble(num);
Py_XDECREF(num);

num = PyNumber_Int(PyTuple_GetItem(args, 2));
supply = PyLong_AsLong(num);
Py_XDECREF(num);

...然后一切都按预期进行。通过此模块运行的其他脚本不会表现出这种行为,并且我看不出有任何差异。他们都调用相同的函数:

SetPowerSupply(37.5, 0.5, 1)
SetPowerSupply(0, 0, 1)

在有问题的脚本中,我可以执行以下操作:

有什么想法吗???

谢谢。

<小时/>

编辑:

该问题是由另一个函数引起的,该函数在此函数之前被多次调用。它是:

if(!PyArg_ParseTuple(args, "s|siss", &board, &component, &pin, &colorStr, &msg))
{
// Parsing the pin as an int failed, try as a string
if(!PyArg_ParseTuple(args, "s|ssss", &board, &component, &sPin, &colorStr, &msg))
{
// ...

这样做的目的基本上是重载第三个参数以接受字符串或数值。当有人向它输入字符串时,解析失败导致的 Python 错误永远不会被清除。解决该问题的更新代码如下。

if(!PyArg_ParseTuple(args, "s|siss", &board, &component, &pin, &colorStr, &msg))
{
PyErr_Clear();

// Parsing the pin as an int failed, try as a string
if(!PyArg_ParseTuple(args, "s|ssss", &board, &component, &sPin, &colorStr, &msg))
{
// ...

非常感谢 Ignacio 提供的线索。

最佳答案

您的其他函数之一未能在适当的时候返回 None,并且您无意中捕获了此错误消息。

关于Python C 接口(interface) PyArg_ParseTuple 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11475070/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com