| 1 |
import py |
| 2 |
from pypy.interpreter.error import OperationError, oefmt |
| 3 |
from pypy.interpreter.gateway import unwrap_spec |
| 4 |
from pypy.interpreter.baseobjspace import W_Root |
| 5 |
from pypy.module._cffi_backend import ctypeobj, ctypeptr, cdataobj |
| 6 |
from pypy.module._cffi_backend.hide_reveal import hide_reveal2 |
| 7 |
from rpython.rtyper.lltypesystem import lltype, llmemory, rffi |
| 8 |
from rpython.rlib import objectmodel, jit |
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
@jit.dont_look_inside |
| 13 |
def _newp_handle(space, w_ctype, w_x): |
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
new_cdataobj = objectmodel.instantiate(cdataobj.W_CDataHandle, |
| 18 |
nonmovable=True) |
| 19 |
_cdata = hide_reveal2().hide_object(rffi.CCHARP, new_cdataobj) |
| 20 |
cdataobj.W_CDataHandle.__init__(new_cdataobj, space, _cdata, w_ctype, w_x) |
| 21 |
return new_cdataobj |
| 22 |
|
| 23 |
@unwrap_spec(w_ctype=ctypeobj.W_CType) |
| 24 |
def newp_handle(space, w_ctype, w_x): |
| 25 |
if (not isinstance(w_ctype, ctypeptr.W_CTypePointer) or |
| 26 |
not w_ctype.is_void_ptr): |
| 27 |
raise oefmt(space.w_TypeError, |
| 28 |
"needs 'void *', got '%s'", w_ctype.name) |
| 29 |
return _newp_handle(space, w_ctype, w_x) |
| 30 |
|
| 31 |
@unwrap_spec(w_cdata=cdataobj.W_CData) |
| 32 |
def from_handle(space, w_cdata): |
| 33 |
ctype = w_cdata.ctype |
| 34 |
if (not isinstance(ctype, ctypeptr.W_CTypePointer) or |
| 35 |
not ctype.is_voidchar_ptr): |
| 36 |
raise oefmt(space.w_TypeError, |
| 37 |
"expected a 'cdata' object with a 'void *' out of " |
| 38 |
"new_handle(), got '%s'", ctype.name) |
| 39 |
with w_cdata as ptr: |
| 40 |
return _reveal(space, ptr) |
| 41 |
|
| 42 |
@jit.dont_look_inside |
| 43 |
def _reveal(space, ptr): |
| 44 |
addr = rffi.cast(llmemory.Address, ptr) |
| 45 |
if not addr: |
| 46 |
raise oefmt(space.w_RuntimeError, |
| 47 |
"cannot use from_handle() on NULL pointer") |
| 48 |
cd = hide_reveal2().reveal_object(cdataobj.W_CDataHandle, addr) |
| 49 |
if cd is None: |
| 50 |
raise oefmt(space.w_SystemError, |
| 51 |
"ffi.from_handle(): dead or bogus object handle") |
| 52 |
return cd.w_keepalive |