PyLong_Check() 错误地检测 PyBool 类型?

问题描述 投票:0回答:1

我在我的 C++ 程序中使用 Python C API。我有一个像这样的函数(简化版),它返回一个字符串,其中包含作为参数传递的给定 PyObject 的类型:

#include <Python.h>

static std::string getPyObjectType(PyObject* obj)
{
  if (PyLong_Check(obj))
  {
    return "long";
  }
  else if (PyFloat_Check(obj))
  {
    return "float";
  }
  else if (PyBool_Check(obj))
  {
    return "bool";
  }
  else
  {
    return "other";
  }
}

问题是没有正确检测布尔对象。当

obj
是布尔值时,它返回
"long"
而不是
"bool"
。就像在这种情况下
PyLong_Check()
错误地返回 true...

如果我在函数中使用断点来检查

obj
的类型,在这种情况下似乎是正确的(它显示
PyBool_Type
):

我的代码出了什么问题?

提前致谢!

python python-c-api
1个回答
0
投票

在检查 float 之前先检查 bool

#include <Python.h>

static std::string getPyObjectType(PyObject* obj)
{
  if (PyLong_Check(obj))
  {
    return "long";
  }
  else if (PyBool_Check(obj))
  {
    return "bool";
  }
  else if (PyFloat_Check(obj))
  {
    return "float";
  }
  else
  {
    return "other";
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.