Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/345.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
当我用Python3的C API构建PyObject时,它的ob_类型为NULL_Python_Python 3.x_C++11_Python C Api - Fatal编程技术网

当我用Python3的C API构建PyObject时,它的ob_类型为NULL

当我用Python3的C API构建PyObject时,它的ob_类型为NULL,python,python-3.x,c++11,python-c-api,Python,Python 3.x,C++11,Python C Api,我在C++11中运行了这样的代码: PyObject* aa = PyLong_FromLong(7L); 然后我检查了aa的值,它不是NULL,而是aa->ob\u type是NULL 然而,当我跑步时: PyObject* aa = PyLong_FromLong(257L); aa->ob_类型不再是空的。我阅读了来自龙的PyLong_文件,发现: PyObject* PyLong_FromLong(long v) Return value: New reference. Retur

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

PyObject* aa = PyLong_FromLong(7L);
然后我检查了
aa
的值,它不是
NULL
,而是
aa->ob\u type
NULL

然而,当我跑步时:

PyObject* aa = PyLong_FromLong(257L);
aa->ob_类型
不再是空的。我阅读了来自龙的PyLong_文件,发现:

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中没有出现。太不可思议了

您还没有初始化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;
}
#包括
#包括
int main(int argc,char*argv[])
{
Py_初始化();
PyObject*aa=PyLong_FromLong(7L);
printf(“aa=%d\naa->ob_type=%p\n”,PyLong_AsLong(aa),aa->ob_type);
Py_Finalize();
返回0;
}
正确打印

aa=7

aa->ob_type=0x7f380d6b5800
(请注意,这将因运行而异)

如果我注释掉
Py\u Initialize()
Py\u Finalize()
,那么我会得到一个分段错误,但是如果我不尝试用
PyLong\u AsLong
读取值,那么我会得到
ob\u type
的空指针


指示您初始化解释器



关于Python2,它有两种整数类型
PyInt
PyLong
,其中
PyInt
处理较小的值,因此具有特殊的大小写表。如果在Python2中使用
PyInt
,您可能会看到同样的问题。但是,在调用
Py\u Initialize
之前使用Python所做的任何事情都是未定义的,因此它可能以不同的令人兴奋的方式失败。

相关:在Python2中有两种整数类型
PyInt
是较小的类型,因此我认为-5->256将在那里定义,而不是用于
PyLong