|
4 | 4 |
|
5 | 5 | from dataclasses import dataclass |
6 | 6 |
|
7 | | -from cuda.core._utils.cuda_utils import driver |
| 7 | +from cuda.core._resource_handles cimport ( |
| 8 | + ContextHandle, |
| 9 | + as_intptr, |
| 10 | + as_py, |
| 11 | +) |
8 | 12 |
|
9 | 13 |
|
10 | | -@dataclass |
11 | | -class ContextOptions: |
12 | | - pass # TODO |
| 14 | +__all__ = ['Context', 'ContextOptions'] |
13 | 15 |
|
14 | 16 |
|
15 | 17 | cdef class Context: |
| 18 | + """CUDA context wrapper. |
16 | 19 |
|
17 | | - cdef: |
18 | | - readonly object _handle |
19 | | - int _device_id |
| 20 | + Context objects represent CUDA contexts and cannot be instantiated directly. |
| 21 | + Use Device or Stream APIs to obtain context objects. |
| 22 | + """ |
20 | 23 |
|
21 | 24 | def __init__(self, *args, **kwargs): |
22 | 25 | raise RuntimeError("Context objects cannot be instantiated directly. Please use Device or Stream APIs.") |
23 | 26 |
|
24 | | - @classmethod |
25 | | - def _from_ctx(cls, handle: driver.CUcontext, int device_id): |
26 | | - cdef Context ctx = Context.__new__(Context) |
27 | | - ctx._handle = handle |
| 27 | + @staticmethod |
| 28 | + cdef Context _from_handle(type cls, ContextHandle h_context, int device_id): |
| 29 | + """Create Context from existing ContextHandle (cdef-only factory).""" |
| 30 | + cdef Context ctx = cls.__new__(cls) |
| 31 | + ctx._h_context = h_context |
28 | 32 | ctx._device_id = device_id |
29 | 33 | return ctx |
30 | 34 |
|
| 35 | + @property |
| 36 | + def handle(self): |
| 37 | + """Return the underlying CUcontext handle.""" |
| 38 | + if self._h_context.get() == NULL: |
| 39 | + return None |
| 40 | + return as_py(self._h_context) |
| 41 | + |
31 | 42 | def __eq__(self, other): |
32 | 43 | if not isinstance(other, Context): |
33 | 44 | return NotImplemented |
34 | 45 | cdef Context _other = <Context>other |
35 | | - return int(self._handle) == int(_other._handle) |
| 46 | + return as_intptr(self._h_context) == as_intptr(_other._h_context) |
36 | 47 |
|
37 | 48 | def __hash__(self) -> int: |
38 | | - return hash(int(self._handle)) |
| 49 | + return hash((type(self), as_intptr(self._h_context))) |
| 50 | + |
| 51 | + |
| 52 | +@dataclass |
| 53 | +class ContextOptions: |
| 54 | + """Options for context creation. |
| 55 | + |
| 56 | + Currently unused, reserved for future use. |
| 57 | + """ |
| 58 | + pass # TODO |
0 commit comments