如何在Cython中调用time.h中的时间?
我想直接用Cython加载time.h,而不是用Python的import time
,但是没成功。
我得到的只是一个错误
Call with wrong number of arguments (expected 1, got 0)
用以下代码
cdef extern from "time.h" nogil:
ctypedef int time_t
time_t time(time_t*)
def test():
cdef int ts
ts = time()
return ts
还有
Cannot assign type 'long' to 'time_t *'
用以下代码
cdef extern from "time.h" nogil:
ctypedef int time_t
time_t time(time_t*)
def test():
cdef int ts
ts = time(1)
return ts
用数学的对数,我可以简单地这样做
cdef extern from "math.h":
double log10(double x)
为什么用time就不行呢?
2 个回答
2
把NULL传给时间函数。另外,你也可以使用内置的libc.time:
from libc.time cimport time,time_t
cdef time_t t = time(NULL)
print t
这样会得到
1471622065
5
在这里,time
函数的参数是一个地址(也就是“指针”),它指向一个time_t
类型的值,用来填充数据,或者可以传入NULL。
引用一下man 2 time
的内容:
time_t time(time_t *t);
[...]
如果传入的参数t不是NULL,那么返回的值也会存储在t指向的内存中。
有些标准函数的设计比较奇怪,它们既会返回一个值,也可能会把这个值存储到你提供的地址里。其实,把0
作为参数传入是完全安全的,因为在大多数情况下,NULL等于((void*)0)
。这样的话,time
函数只会返回结果,而不会尝试把结果存储到你提供的地址里。