| 369 | |
| 370 | |
| 371 | def _pybuffer2numpy(frame: _TreelitePyBufferFrame) -> np.ndarray: |
| 372 | if platform.python_implementation() != "CPython": |
| 373 | raise NotImplementedError("_pybuffer2numpy() not supported on PyPy") |
| 374 | if not frame.buf: |
| 375 | if frame.format == b"=l": |
| 376 | dtype = "int32" |
| 377 | elif frame.format == b"=Q": |
| 378 | dtype = "uint64" |
| 379 | elif frame.format == b"=L": |
| 380 | dtype = "uint32" |
| 381 | elif frame.format == b"=B": |
| 382 | dtype = "uint8" |
| 383 | elif frame.format == b"=f": |
| 384 | dtype = "float32" |
| 385 | elif frame.format == b"=d": |
| 386 | dtype = "float64" |
| 387 | else: |
| 388 | raise RuntimeError( |
| 389 | f"Unrecognized format string: {frame.format.decode('utf-8')}" |
| 390 | ) |
| 391 | return np.array([], dtype=dtype) |
| 392 | py_buf = _PyBuffer() |
| 393 | py_buf.buf = frame.buf |
| 394 | py_buf.obj = ctypes.py_object(frame) |
| 395 | py_buf.len = frame.nitem * frame.itemsize |
| 396 | py_buf.itemsize = frame.itemsize |
| 397 | py_buf.readonly = 0 |
| 398 | py_buf.ndim = 1 |
| 399 | py_buf.format = frame.format |
| 400 | py_buf.shape = (ctypes.c_ssize_t * 1)(frame.nitem) |
| 401 | py_buf.strides = (ctypes.c_ssize_t * 1)(frame.itemsize) |
| 402 | py_buf.suboffsets = None |
| 403 | py_buf.internal = None |
| 404 | |
| 405 | view: memoryview = ctypes.pythonapi.PyMemoryView_FromBuffer(ctypes.byref(py_buf)) |
| 406 | return np.asarray(view) |
| 407 | |
| 408 | |
| 409 | def _numpy2pybuffer(array: np.ndarray) -> _TreelitePyBufferFrame: |