【问题标题】:Cython fused can not castingCython 融合无法铸造
【发布时间】:2016-04-10 05:43:31
【问题描述】:
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

上面的代码给我一个错误(类型不是专门的),任何人都知道如何解决这个问题,谢谢。

【问题讨论】:

  • 它会给你什么样的错误?此外,您设置 idx 值的那一行也很疯狂。你想做什么?我们很有可能可以简化它。
  • 抱歉代码不清楚,我想返回数组中的目标位置,谢谢。

标签: python cython


【解决方案1】:

您可以使用方括号(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 必须都是相同的类型)。这是(我认为?)你出错的地方。

【讨论】:

    【解决方案2】:

    你有几个语法问题,我认为你只是让这有点太复杂了。另外据我所知,您必须为 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)
    

    【讨论】:

      猜你喜欢
      • 2021-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-07
      • 1970-01-01
      • 2014-01-28
      相关资源
      最近更新 更多