当使用Python3的C API构建PyObject时,它的ob_type为NULL

2024-09-28 01:26:36 发布

您现在位置:Python中文网/ 问答频道 /正文

<>我在C++ 11中运行了这样的代码:

PyObject* aa = PyLong_FromLong(7L);

然后我检查了aa的值,它不是NULL,而是{}是{}。在

但是,当我跑的时候:

^{pr2}$

aa->ob_type不再是NULL。我读了PyLong_FromLong的文件,发现了这个:

PyObject* PyLong_FromLong(long v)
Return value: New reference. 
Return a new PyLongObject object from v, or NULL on failure.

The current implementation keeps an array of integer objects for all integers between -5 and 256, when you create an int in that range you actually just get back a reference to the existing object. So it should be possible to change the value of 1. I suspect the behaviour of Python in this case is undefined. :-)

似乎在-5和256之间构建PyLongObject时会遇到这个问题。但我不明白原因。在

更重要的是,这个问题在Python2中没有出现。太不可思议了!在


Tags: oftheinyouanreturnobjectvalue
1条回答
网友
1楼 · 发布于 2024-09-28 01:26:36

您尚未初始化Python。因为这些小对象是特殊大小写的,所以它们是在Python初始化时设置的。在

#include <Python.h>
#include <stdio.h>

int main(int argc, char *argv[])
{
  Py_Initialize();
  PyObject* aa = PyLong_FromLong(7L);
  printf("aa=%d\naa->ob_type=%p\n",PyLong_AsLong(aa),aa->ob_type);
  Py_Finalize();
  return 0;
}

正确打印

aa=7

aa->ob_type=0x7f380d6b5800 (note that this will vary from run to run)

如果我注释掉Py_Initialize()Py_Finalize(),那么我会得到一个分段错误,但是如果我不尝试用PyLong_AsLong读取值,那么我会得到一个ob_type的空指针。在


The documentation确实告诉您初始化解释器。在


对于Python2,它有两个整数类型PyInt和{},其中{}处理小值,因此有特殊的大小写表。如果在Python2中使用PyInt,您可能会看到相同的问题。但是,在调用Py_Initialize之前对Python所做的任何操作都是未定义的,因此它可能会以不同的令人兴奋的方式失败。在

相关问题 更多 >

    热门问题