error: value of type 'PyObject' (aka '_object') is not contextually convertible to 'bool'

error: value of type 'PyObject' (aka '_object') is not contextually convertible to 'bool'

我正在将 python 模块作为 PyObject 传递给 C。我想检查这个值在我的 C 代码中是否为 NONE,使用以下形式:

int func(PyObject tmp)
{
   if(tmp)
    { 
     // etc

我收到以下错误。如何将 PyObject 转换为布尔值,类似于 Python 的 if 函数行为方式。值得注意的是,当 tmp 是一个 boost::python::object 变量时,此命令按预期工作。

ex_program.cpp:72:7: error: value of type 'PyObject' (aka '_object') is not contextually convertible to 'bool'
  if (tmp)
      ^~~

PyObject_IsTrue seems to do what you want:

int PyObject_IsTrue(PyObject *o)

    Returns 1 if the object o is considered to be true, and 0 otherwise. This is equivalent to the Python expression not not o. On failure, return -1.