[英]Checking A PyObjects C Type
我正在使用 Python 3.2 和 C++。
我需要提取当前存储在 PyObject 中的是哪种 C 类型。 我已经检查了文档并用谷歌搜索了它,似乎没有其他人需要这样做。
所以我有一个 PyObject 并试图提取 C 值。 我有需要从 object 中实际提取值的函数列表,但我首先需要知道的是存储在 object 本身中的内容以调用正确的 function。
以防万一这有助于理解这里是我正在尝试的一些示例代码。
//Variable is a custom variant type to allow for generic functionality.
Variable ExtractArgument( PyObject * arg )
{
Variable value;
PyObject* result;
//now here is the problem, I need to know which Python function to call in order to
//extract the correct type;
value = PyLong_FromLong( arg );
//or
value = PyFloat_FromDouble( arg )
//ect.
return value;
}
希望我能有一些看起来像这样的东西
Variable ExtractArgument( PyObject * arg )
{
Variable value;
PyObject* result;
//PyType is not the actual variable to that holds the type_macro, GetType should be
//replaced by the function I am trying to find
PyType type = GetType( arg );
switch( type )
{
case T_INT: value = static_cast<int>(PyLong_FromLong( arg ));
break;
case T_FLOAT: value = static_cast<float>(PyFloat_FromDouble( arg ));
break;
case T_DOUBLE: value = PyDouble_FromDouble( arg );
break;
//ect.
}
return value;
}
对不起,如果这个问题太长或信息太多。 第一次发帖,不想留下任何可能有帮助的东西。 感谢您在此问题上提供的任何帮助或见解。
Python 对象没有 C 类型,它们有 Python 类型。 例如,integer 可以是长 C 或长 integer。 您可以使用PyInt_Check(obj)
、 PyList_Check(obj)
等检查类型。如果返回 true,那么您知道您拥有该类型的 object。
请注意PyLong_FromLong
和这样的 go 是另一种方式。 他们采用 C 值并将其转换为 PyObject*。 因此,您正在向后使用它们。 我认为您的意思是PyInt_AsLong
。
这不是 Python 类型的工作原理; 他们不是一对一的 map 到 C 类型。 There is no Python C/API function that will tell you what C type a particular value will fit in. There are, however, functions like PyFloat_Check()
and PyInt_Check()
that check the type (and consider subclasses as well.) There are PyArg_ParseTuple()
(及其变体)的说明符告诉 Python 适当地转换传入的参数。
通常使用的是后者; decode the arguments passed to a C function with PyArg_ParseTuple()
, and if you need different types being passed treated differently, pass them as different arguments (usually as named arguments.) It's not clear if that approach can work for you. 第二个最常见的做法是尝试使用不同的函数转换参数而不先进行类型检查,然后在转换失败时简单地尝试另一个转换 function。 显式类型检查通常是最不常见的替代方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.