Files
SPHLite/Python/sphlite_debug.py
T
2026-07-02 18:47:38 +08:00

67 lines
2.1 KiB
Python

from __future__ import annotations
import ctypes
from pathlib import Path
class SPHLiteError(RuntimeError):
pass
class SPHLite:
def __init__(self, library: str | Path):
self.library_path = Path(library)
self.lib = ctypes.CDLL(str(self.library_path))
self._configure()
def _configure(self) -> None:
self.lib.sphlite_initialize.restype = ctypes.c_int
self.lib.sphlite_finalize.restype = ctypes.c_int
self.lib.sphlite_read_inp.argtypes = [ctypes.c_char_p]
self.lib.sphlite_read_inp.restype = ctypes.c_int
self.lib.sphlite_build_model.restype = ctypes.c_int
self.lib.sphlite_run_explicit.restype = ctypes.c_int
self.lib.sphlite_get_particle_count.argtypes = [ctypes.POINTER(ctypes.c_int)]
self.lib.sphlite_get_particle_count.restype = ctypes.c_int
self.lib.sphlite_get_last_error.argtypes = [
ctypes.POINTER(ctypes.c_int),
ctypes.c_char_p,
ctypes.c_int,
]
self.lib.sphlite_get_last_error.restype = ctypes.c_int
def _check(self, ierr: int) -> None:
if ierr == 0:
return
code = ctypes.c_int(0)
buffer = ctypes.create_string_buffer(256)
rc = self.lib.sphlite_get_last_error(ctypes.byref(code), buffer, len(buffer))
if rc == 0:
raise SPHLiteError(buffer.value.decode("utf-8", errors="replace"))
raise SPHLiteError(f"SPHLite error {ierr}")
def initialize(self) -> None:
self._check(self.lib.sphlite_initialize())
def finalize(self) -> None:
self._check(self.lib.sphlite_finalize())
def read_inp(self, filename: str | Path) -> None:
encoded = str(Path(filename)).encode("utf-8")
self._check(self.lib.sphlite_read_inp(encoded))
def build_model(self) -> None:
self._check(self.lib.sphlite_build_model())
def particle_count(self) -> int:
count = ctypes.c_int(0)
self._check(self.lib.sphlite_get_particle_count(ctypes.byref(count)))
return int(count.value)
def run_explicit(self) -> None:
self._check(self.lib.sphlite_run_explicit())