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

我将一个python模块传递给C作为PyObject 。 我想使用以下表单检查我的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) ^~~ 

PyObject_IsTrue似乎做你想要的 :

 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.