【问题标题】:Numba jit nopython - how to test for null pointerNumba jit nopython - 如何测试空指针
【发布时间】:2020-05-19 08:44:48
【问题描述】:

在大量使用 numba 之后,我遇到了一个非常基本的问题。如何检查 NULL 指针? 这一定是微不足道的,但我似乎无法弄清楚。请参阅下面 sn-p 中的 cmets。 我正在尝试实现 C 回调

import numba as nb
from numba.core.typing import cffi_utils,ctypes_utils
import ctypes
from cffi import FFI
ffi=FFI()
ffi.cdef('void (*fun)(int n, double* x)')
sig = cffi_utils.map_type(ffi.typeof('fun'))

# how to define NullPtr ?
# None of the following works
NullPtr = ffi.NULL 
NullPtr = None
NullPtr = ctypes.POINTER(ctypes.c_void_p)()

@nb.cfunc(sig)
def fun(n, x):
    # if x: doesn't  work
    # if x == 0: doesn't  work
    if x == NullPtr: # doesn't  work either 
        pass
    else:
        # do stuff with x
        pass

【问题讨论】:

    标签: numba


    【解决方案1】:

    好的,我想出了一个解决方案,但我不敢相信它应该是这样的

    from numba.extending import intrinsic
    from numba.core import cgutils
    
    @intrinsic
    def is_null_ptr(typingctx, src):
        if isinstance(src, types.CPointer):
            sig  = types.boolean(src)
            def codegen(context, builder, signature, args):
                [src] = args
                return cgutils.is_null(builder,src)
            return sig, codegen
    

    用法:

    @nb.cfunc(sig)
    def fun(n, x):
        if is_null_ptr(x):
            pass
        else:
            # do stuff with x
            pass
    

    【讨论】:

      猜你喜欢
      • 2020-08-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-10
      • 2018-03-19
      • 1970-01-01
      • 2018-01-18
      • 2012-12-26
      相关资源
      最近更新 更多