错误:'PyObject'(又名'_object')类型的值不能在上下文中转换为'bool'

时间:2015-07-09 22:05:41

标签: python c python-c-api pyobject

我将一个python模块作为PyObject传递给C.我想使用以下格式检查我的C代码中的值是否为NONE:

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

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

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

1 个答案:

答案 0 :(得分:1)

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.