从 numba 使用 jitclass 时如何返回字符串?

How returning a string when using jitclass from numba?

当我在使用 jitclass 的 class 中调用一个函数时,我试图 return 一个字符串,但我得到一个错误:

numba.errors.InternalError: Failed at nopython (nopython mode backend)
cannot convert native const('Something') to Python object
[1] During: resolving callee type: BoundFunction((<class 'numba.types.misc.ClassInstanceType'>, 'get_Names') for     instance.jitclass.myclass#3f2d488<A:float64,B:float64>)
[2] During: typing of call at <string> (3)

我正在使用这段代码来测试功能:

from numba import jitclass
from numba import boolean, int32, float64,uint8

spec = [('A' ,float64),
        ('B' ,float64)]

@jitclass(spec)
class myclass:

    def __init__(self,):
        self.A = 3.25
        self.B = 22.5

    def get_Names(self):
        return "Something"



mC = myclass()
print(mC.get_Names())

有人知道我如何 return 字符串吗?

您可以通过使用字节数组来表示字符串来解决这个问题,如下所示。

话虽如此,我认为 ugly/hard 维护起来很不错。假设它符合问题,我认为你最好使用带有 jit 函数的普通 python class 来根据需要进行加速,或者使用 cython 之类的更丰富的东西支持扩展类型。

from numba import jitclass, float64

SOMETHING = np.frombuffer(b"Something", dtype='uint8')

spec = [('A' ,float64),
        ('B' ,float64)]

def get_jitclass_str(val):
    return bytes(val).decode('utf-8')

@jitclass(spec)
class myclass:

    def __init__(self,):
        self.A = 3.25
        self.B = 22.5

    def get_Names(self):
        return SOMETHING

用法

In [16]: mc = myclass()

In [17]: get_jitclass_str(mc.get_Names())
Out[17]: 'Something'