Commit bebb9b54 authored by gabrieldemarmiesse's avatar gabrieldemarmiesse

switching long for uintptr_t, and rephrasing some parts.

parent 31c06c49
...@@ -526,26 +526,33 @@ Where C uses ``"("`` and ``")"``, Cython uses ``"<"`` and ``">"``. For example:: ...@@ -526,26 +526,33 @@ Where C uses ``"("`` and ``")"``, Cython uses ``"<"`` and ``">"``. For example::
cdef float *q cdef float *q
p = <char*>q p = <char*>q
If one of the types is a Python object for ``<type>x``, Cython will try to do a coercion. When casting a C value to a Python object type or vice versa,
Cython will attempt a coercion. Simple examples are casts like ``<int>pyobj``,
which converts a Python number to a plain C ``int`` value, or ``<bytes>charptr``,
which copies a C ``char*`` string into a new Python bytes object.
.. note:: Cython will not stop a casting where there is no conversion, but it will emit a warning. .. note:: Cython will not prevent a redundant cast, but emits a warning for it.
To get the address of some Python object, use a cast to a pointer type To get the address of some Python object, use a cast to a pointer type
like ``<void*>`` or ``<PyObject*>``. like ``<void*>`` or ``<PyObject*>``.
You can also get the python object from a pointer to this object by doing ``<object>``. You can also cast a C pointer back to a Python object reference
with ``<object>``, or a more specific builtin or extension type
(e.g. ``<MyExtType>ptr``). This will increase the reference count of
the object by one, i.e. the cast returns an owned reference.
Here is an example:: Here is an example::
from __future__ import print_function from __future__ import print_function
from cpython.ref cimport PyObject from cpython.ref cimport PyObject
from libc.stdint cimport uintptr_t
python_string = "foo" python_string = "foo"
cdef void* ptr = <void*>python_string cdef void* ptr = <void*>python_string
cdef long adress_in_c = <long>ptr cdef uintptr_t adress_in_c = <uintptr_t>ptr
address_from_void = adress_in_c # address_from_void is a python int address_from_void = adress_in_c # address_from_void is a python int
cdef PyObject* ptr2 = <PyObject*>python_string cdef PyObject* ptr2 = <PyObject*>python_string
cdef long address_in_c2 = <long>ptr2 cdef uintptr_t address_in_c2 = <uintptr_t>ptr2
address_from_PyObject = address_in_c2 # address_from_PyObject is a python int address_from_PyObject = address_in_c2 # address_from_PyObject is a python int
assert address_from_void == address_from_PyObject == id(python_string) assert address_from_void == address_from_PyObject == id(python_string)
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment