python - 检查 PyObjects C 类型

标签 python c++ 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;
}

希望我能有这样的东西

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 类型。例如,整数可以是 C long 或 long 整数。您可以使用 PyInt_Check(obj)PyList_Check(obj) 等检查类型。如果返回 true,那么您就知道您拥有该类型的对象。

请注意 PyLong_FromLong 等是相反的。他们采用 C 值并将其转换为 PyObject*。所以你在倒着使用它们。我想你的意思是 PyInt_AsLong

关于python - 检查 PyObjects C 类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6103847/

相关文章:

python - 为什么在通过 Python 的 C API 调用 pyplot.draw() 时重新播种 rand()?

python - 导入错误:C 扩展:没有名为 'parsing' 的模块未构建

python - NumPy C API 扩展导致内存使用过多

python - 将元素添加/append 到 python 列表

python - 如何设置Django的默认值 'on_delete=models.SET_DEFAULT'

C++11 `using` 关键字 : specialize template alias of template parameter

c++ - 是为类的用户覆盖还是为实现者覆盖?

python - XGBoost:将 dmatrix 转换为 numpy.array

python 枕头 : Add transparent gradient to an image

c++ - 将字符串变量输出到 HEX 格式的文本文件中