我在使用jitclass
的类中调用函数时尝试返回字符串,但是我收到错误:
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())
有人知道如何返回字符串吗?
答案 0 :(得分:2)
您可以通过使用字节数组来表示字符串来解决这个问题,如下所示。
那就是说,我觉得这很丑陋/难以维持。假设它适合这个问题,我认为你最好在必要时使用带有jit
函数的普通python类来加速,或者放入像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'