我正在使用Python 3.2和C++。检查PyObjects C类型
我需要提取当前存储在PyObject中的什么类型的C类型。 我已经检查了文档并搜索了它,似乎没有其他人需要这样做。
所以我有一个PyObject,并试图提取C值。我有需要从对象中实际提取值的函数列表,但我首先需要知道的是正在存储在对象本身中以调用正确的函数。
为了以防万一这有助于理解这里是我正在尝试的一些示例代码。
//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;
}
很抱歉,如果这个问题是长期或过多的信息。第一次发布,不想留下任何可能有帮助的东西。 感谢您对此问题给予的任何帮助或见解。
是的,我的意思是PyInt。 – DaneEC117 2011-05-23 23:00:41
这似乎是迄今为止我必须尝试的最佳选择。我“可能”遇到了一些类型冲突,因为python并没有存储我需要的所有类型,所以我很可能会结合检查C++函数期望的类型来执行此操作。 – DaneEC117 2011-05-23 23:08:16
你正在编写一个C++函数的Python包装器吗?听起来你正在重新发明SWIG。 – Adam 2011-05-23 23:11:13