C++ 扩展中的 DateTime 对象方法出现问题

Trouble with DateTime object methods in C++ extension

我正在为 Python 3 开发 C++ 扩展,并试图将 DateTime 对象传递给我的函数。 PyDateTime_Check 函数似乎有效并且 return 是正确的,但是当我尝试从 DateTime 对象获取年份时它 returns 65535。我正在传递 datetime.datetime.now( ) 从 python.

进入函数

我的 C++ 代码是:

#include "Python.h"
#include "datetime.h"

static PyObject* new_func(Pyobject* self, PyObject* args)
{
    PyDateTime_DateTime *pydate;
    if(!PyArg_ParseTuple(args, "O", &pydate)){
        return Py_BuildValue("s", "Error");
    }
    int year;
    year = PyDateTime_GET_YEAR(pydate);
    return PyLong_FromLong(year);
}

static PyMethodDef NbourMethods[] =
{
     {"new_func", new_func, METH_VARARGS, "Do date things."},
     {NULL, NULL, 0, NULL}
};

static struct PyModuleDef cFunc =
{
  PyModuleDef_HEAD_INIT,
  "cFunc", /* name of module */
  "",     /* module documentation */
  -1,     /* size of per-interpreter state of the module or -1 if global */
  NbourMethods
};

PyMODINIT_FUNC PyInit_cFunc(void)
{
  if (!PyDateTimeAPI) { PyDateTime_IMPORT;}
  return PyModule_Create(&cFunc);
}

那么我的python代码是:

import cFunc
start = datetime.datetime.now()
print(str(cFunc.new_func(start)))

有什么想法吗?我能够成功 运行 PyDateTime_Check(pydate) 并获得 return 值 true,但由于某种原因它不会 return 上面代码中的年份(returns 65535)。提前致谢!

因此,在多加考虑之后,编译器和 python 库似乎都存在问题。改变这些产生了预期的结果。我在下面确实遇到了一个奇怪的 hack,但是每次加载扩展模块时都会用掉大约 4GB 的 RAM -> 表明发生了更多错误。似乎是 MinGW 中的一个潜在问题。

我原来的解决方案:

所以只是闲逛并查看底层 datetime.h 并进行一些探索 - PyObject 中似乎有 4 个字节未使用。不知道为什么会这样。

临时修复是通过引用字节 4 和 5(而不是函数中的 0 和 1)来 return 年份:

year = ((((PyDateTime_Date *)pydate)->data[4] << 8) | ((PyDateTime_Date *)pydate)->data[5]);

这不是很好,但是另一种方法是在导入 datetime.h 之后定义我自己的 GET_YEAR 函数:

#define PyDateTime_GET_YEAR_NEW(o)     ((((PyDateTime_Date*)o)->data[4] << 8) | \
                 ((PyDateTime_Date*)o)->data[5])

那么函数中的return可以是:

return PyLong_FromLong(PyDateTime_GET_YEAR_NEW(pydate));