检查PyObjects C类型

Dan*_*117 5 c++ python python-c-api

我使用的是Python 3.2和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;
}
Run Code Online (Sandbox Code Playgroud)

希望我能看到类似这样的东西

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;
} 
Run Code Online (Sandbox Code Playgroud)

对不起,如果这个问题很长或太多信息.第一次发布,并不想留下任何可能有帮助的东西.感谢您在此问题上给我的任何帮助或见解.

Ada*_*dam 5

Python对象没有C类型,它们具有Python类型.例如,整数可以是C长整数或长整数.您可以使用PyInt_Check(obj),PyList_Check(obj)等检查类型.如果返回true,则表示您拥有该类型的对象.

请注意,PyLong_FromLong这样做是另一回事.它们取一个C值并将其转换为PyObject*.所以你正在向后使用它们.我想你的意思PyInt_AsLong.

  • *Boost的问题在于它是编译时间和模板地狱.我们喜欢我们的游戏引擎在大约4秒内编译并且几乎没有外部依赖,除了DirectX和Fmod之类的东西. (3认同)