【发布时间】:2016-10-09 21:00:18
【问题描述】:
我有一个变量PyObject,我知道它是一个 Python 布尔值。它可以是True 或False(例如Py_True 或Py_False)。现在我想以某种方式将其转换为 C++。
用字符串做这件事并不难,有一个辅助函数 - PyBytes_AsString 将 python 字符串转换为 C 字符串。现在我需要类似的布尔值(或 int,因为 C 中没有 bool)。
或者如果没有转换,也许一些可以比较真假的函数? int PyBool_IsTrue(PyObject*) 之类的东西?
以下是一些示例代码,便于理解我的需求:
#include <Python.h>
int main()
{
/* here I create Python boolean with value of True */
PyObject *b = Py_RETURN_TRUE;
/* now that I have it I would like to turn in into C type so that I can determine if it's True or False */
/* something like */
if (PyBool_IsTrue(b))
{ /* it's true! */ }
else
{ /* it's false */ }
return 0;
}
这显然行不通,因为没有像 PyBool_IsTrue 这样的功能 :( 我该怎么做?
Python 标头 (boolobject.h) 的片段:
/* Boolean object interface */
#ifndef Py_BOOLOBJECT_H
#define Py_BOOLOBJECT_H
#ifdef __cplusplus
extern "C" {
#endif
PyAPI_DATA(PyTypeObject) PyBool_Type;
#define PyBool_Check(x) (Py_TYPE(x) == &PyBool_Type)
/* Py_False and Py_True are the only two bools in existence.
Don't forget to apply Py_INCREF() when returning either!!! */
/* Don't use these directly */
PyAPI_DATA(struct _longobject) _Py_FalseStruct, _Py_TrueStruct;
/* Use these macros */
#define Py_False ((PyObject *) &_Py_FalseStruct)
#define Py_True ((PyObject *) &_Py_TrueStruct)
/* Macros for returning Py_True or Py_False, respectively */
#define Py_RETURN_TRUE return Py_INCREF(Py_True), Py_True
#define Py_RETURN_FALSE return Py_INCREF(Py_False), Py_False
/* Function to return a bool from a C long */
PyAPI_FUNC(PyObject *) PyBool_FromLong(long);
#ifdef __cplusplus
}
#endif
#endif /* !Py_BOOLOBJECT_H */
【问题讨论】:
-
投反对票的原因?
标签: python c python-c-api