@@ -18,8 +18,9 @@ class TypeCode(object):
1818 ARRAY_HANDLE = 5
1919 TVM_TYPE = 6
2020 NODE_HANDLE = 7
21- STR = 8
22- FUNC_HANDLE = 9
21+ FUNC_HANDLE = 8
22+ STR = 9
23+ BYTES = 10
2324
2425def _api_type (code ):
2526 """create a type accepted by API"""
@@ -88,6 +89,11 @@ class TVMValue(ctypes.Union):
8889 ("v_handle" , ctypes .c_void_p ),
8990 ("v_str" , ctypes .c_char_p )]
9091
92+ class TVMByteArray (ctypes .Structure ):
93+ """TVM datatype structure"""
94+ _fields_ = [("data" , ctypes .POINTER (ctypes .c_byte )),
95+ ("size" , ctypes .c_size_t )]
96+
9197
9298TVMPackedCFunc = ctypes .CFUNCTYPE (
9399 None ,
@@ -110,20 +116,34 @@ def _return_handle(x):
110116 handle = ctypes .c_void_p (handle )
111117 return handle
112118
119+ def _return_bytes (x ):
120+ """return handle"""
121+ handle = x .v_handle
122+ if not isinstance (handle , ctypes .c_void_p ):
123+ handle = ctypes .c_void_p (handle )
124+ arr = ctypes .cast (handle , ctypes .POINTER (TVMByteArray ))[0 ]
125+ size = arr .size
126+ res = bytearray (size )
127+ rptr = (ctypes .c_byte * size ).from_buffer (res )
128+ if not ctypes .memmove (rptr , arr .data , size ):
129+ raise RuntimeError ('memmove failed' )
130+ return res
131+
113132
114133RETURN_SWITCH = {
115134 TypeCode .INT : lambda x : x .v_int64 ,
116135 TypeCode .FLOAT : lambda x : x .v_float64 ,
117136 TypeCode .HANDLE : _return_handle ,
118137 TypeCode .NULL : lambda x : None ,
119- TypeCode .STR : lambda x : py_str (x .v_str )
138+ TypeCode .STR : lambda x : py_str (x .v_str ),
139+ TypeCode .BYTES : _return_bytes
120140}
121141
122-
123142C_TO_PY_ARG_SWITCH = {
124143 TypeCode .INT : lambda x : x .v_int64 ,
125144 TypeCode .FLOAT : lambda x : x .v_float64 ,
126145 TypeCode .HANDLE : _return_handle ,
127146 TypeCode .NULL : lambda x : None ,
128- TypeCode .STR : lambda x : py_str (x .v_str )
147+ TypeCode .STR : lambda x : py_str (x .v_str ),
148+ TypeCode .BYTES : _return_bytes
129149}
0 commit comments