Cython fused 无法铸造

Cython fused can not casting

cdef int bs_contains_nogil(float_or_int[:] l,float_or_int t,int size) nogil:
    cdef int low=0
   cdef int high=size-1
   cdef int mid=0
   while(low<=high):
        mid=(low+high)//2
        if t==l[mid]:
            return mid
        elif t < l[mid]:
            high=mid-1
        else:
            low=mid+1
    return -(low+1)

@boundscheck(False)
@wraparound(False)
def insertplace_nogil(l,t):
   idx=(<object (*)(int[:],int,int)>bs_contains_nogil)(l,t,len(l))
   return idx //return the target position

上面的代码给我一个错误(Type is not specialized),任何人都知道如何解决这个问题,谢谢。

您有几个语法问题,我认为您把它弄得太复杂了。另外据我所知,您必须为 cdef 函数的参数选择一种类型,或者改用 python 对象,这可能就是您收到与类型相关的错误的原因。我还没有测试过这个,但试一试

cdef int bs_contains_nogil(int[:] l, int t,int size) nogil:
    cdef int low=0
    cdef int high=size-1
    cdef int mid=0
    while(low<=high):
        mid=(low+high)/2
        if t==l[mid]:
            return mid
        elif t < l[mid]:
            high=mid-1
        else:
            low=mid+1
    return low+1

@boundscheck(False)
@wraparound(False)
def insertplace_nogil(l,t):
    return bs_contains_nogil(l,t,len(l)

您可以 select 使用方括号 (as discussed in the documentation).

轻松地对您的融合类型函数进行 int 特化
# for completeness
ctypedef fused float_or_int:
    float
    int

cdef int bs_contains_nogil(float_or_int[:] l,float_or_int t,int size) nogil:
    return 5 # your function goes here... I've cut this down for simplicitity since I don't think it's the main point of your question.

def insertplace_nogil(l,t):
    return bs_contains_nogil[int](l,t,len(l))

请注意,您只需指定一次类型(即 lt 必须是同一类型)。这是(我想?)你出错的地方。