Numba jit nopython - 如何测试空指针?

问题描述 投票:0回答:1

在使用了很多numba之后,我被一个很基本的问题所困扰,如何检查NULL指针?如何检查NULL指针?这一定是个小问题,但我似乎无法解决。请看下面的代码段中的注释。

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个回答
0
投票

好吧,我想出了一个解决方案,但我很难相信它应该是这样的。

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
© www.soinside.com 2019 - 2024. All rights reserved.