def test_from_ctypes(self): """ Test converting a ctypes type to a Numba type. """ def check(cty, ty): got = ctypes_utils.from_ctypes(cty) self.assertEqual(got, ty) self._conversion_tests(check) # An unsupported type with self.assertRaises(TypeError) as raises: ctypes_utils.from_ctypes(c_wchar_p) self.assertIn("Unsupported ctypes type", str(raises.exception))
def carray(ptr, shape, dtype=None): """ Return a Numpy array view over the data pointed to by *ptr* with the given *shape*, in C order. If *dtype* is given, it is used as the array's dtype, otherwise the array's dtype is inferred from *ptr*'s type. """ from numba.core.typing.ctypes_utils import from_ctypes try: # Use ctypes parameter protocol if available ptr = ptr._as_parameter_ except AttributeError: pass # Normalize dtype, to accept e.g. "int64" or np.int64 if dtype is not None: dtype = np.dtype(dtype) if isinstance(ptr, ctypes.c_void_p): if dtype is None: raise TypeError("explicit dtype required for void* argument") p = ptr elif isinstance(ptr, ctypes._Pointer): ptrty = from_ctypes(ptr.__class__) assert isinstance(ptrty, types.CPointer) ptr_dtype = as_dtype(ptrty.dtype) if dtype is not None and dtype != ptr_dtype: raise TypeError("mismatching dtype '%s' for pointer %s" % (dtype, ptr)) dtype = ptr_dtype p = ctypes.cast(ptr, ctypes.c_void_p) else: raise TypeError("expected a ctypes pointer, got %r" % (ptr, )) nbytes = dtype.itemsize * np.product(shape, dtype=np.intp) return _get_array_from_ptr(p, nbytes, dtype).reshape(shape)
def check(cty, ty): got = ctypes_utils.from_ctypes(cty) self.assertEqual(got, ty)