i遵循this answer调用^ {< CD1>},以在C++中创建^ {< CD2>}对象。但是当调用PyDateTime_FromTimestamp
时,我得到了一个Segmentation fault
。你知道吗
这是我的C++代码:
#include <python3.6/Python.h>
#include <stdio.h>
#include <python3.6/datetime.h>
#include <sys/time.h>
static PyObject *iGetDateTime_PyFn(PyObject *Py_UNUSED(self), PyObject *Py_UNUSED(args)) {
static double doubleValue = 1314761451;
PyObject *floatObj = NULL;
PyObject *timeTuple = NULL;
PyObject *dateTime = NULL;
floatObj = PyFloat_FromDouble(doubleValue);
timeTuple = Py_BuildValue("(O)", floatObj);
printf("timeTuple = %08x\n", (unsigned int)(long long)timeTuple);
printf("PyTuple_Check(timeTuple) = %d\n", PyTuple_Check(timeTuple));
dateTime = PyDateTime_FromTimestamp(timeTuple);
printf("ready to return\n");
return dateTime;
}
static PyMethodDef all_methods[] = {
{ "get_datetime", iGetDateTime_PyFn, METH_VARARGS, NULL },
{ NULL, NULL, 0, NULL }
};
static struct PyModuleDef main_module = {
PyModuleDef_HEAD_INIT,
"cpp",
NULL,
-1,
all_methods
};
PyMODINIT_FUNC PyInit_cpp(void) {
return PyModule_Create(&main_module);
}
我用这个命令编译:
g++ --shared -fPIC -o cpp.so t1.cpp
我的g++
版本是7.3.0
。你知道吗
在python中,我执行:
import cpp
print(cpp.get_datetime())
我打印了以下内容:
timeTuple = a7934358
PyTuple_Check(timeTuple) = 1
Segmentation fault (core dumped)
正如我们所看到的,timeTuple
被成功构造,并被检查为tuple
。但是我们无法理解return
这个句子。你知道吗
根据[GitHub]: python/cpython - (3.6) cpython/Include/datetime.h(${PYTHON\u SRC\u DIR}/Include/datetime.h):
PyDateTime\u FromTimestamp是一个预处理器宏:
PyDateTimeAPI初始化为NULL(文件前面)
在调用宏时导致segfault(访问冲突)。你知道吗
修复需要通过PyDateTime\u IMPORT宏初始化PyDateTimeAPI。你知道吗
起初,我在浏览代码时发现了这个问题(我在getDateTimePyFn函数中发现了这个问题),然后我遇到了[Python 3.Docs]: DateTime Objects(emphasis是我的)
我修改了你的代码,我将在Win上举例说明(因为这对我来说更容易,而且行为是可复制的)。你知道吗
cpp.c公司:
代码.py:
输出:
相关问题 更多 >
编程相关推荐