Commit 01fd4fe4 authored by gabrieldemarmiesse's avatar gabrieldemarmiesse

Transfered type casting

parent eb18ac4c
......@@ -381,6 +381,48 @@ Sometimes Cython will complain unnecessarily, and sometimes it will fail to
detect a problem that exists. Ultimately, you need to understand the issue and
be careful what you do.
Type Casting
------------
As C uses the ``"("`` and ``")"`` for casting types, Cython uses ``"<"`` and ``">"``
to signify a casting. For example::
cdef char *p
cdef float *q
p = <char*>q
If one of the types is a Python object for ``<type>x``, Cython will try to do a coercion.
.. note:: Cython will not stop a casting where there is no conversion, but it will emit a warning.
To get the address of some Python object, use a cast to a pointer type
like ``<void*>`` or ``<PyObject*>``.
You can also get the python object from a pointer to this object by doing ``<object>``.
Here is an example::
from __future__ import print_function
from cpython.ref cimport PyObject
python_string = "foo"
cdef void* ptr = <void*>python_string
cdef long adress_in_c = <long>ptr
address_from_void = adress_in_c # address_from_void is a python int
cdef PyObject* ptr2 = <PyObject*>python_string
cdef long address_in_c2 = <long>ptr2
address_from_PyObject = address_in_c2 # address_from_PyObject is a python int
assert address_from_void == address_from_PyObject == id(python_string)
print(<object>ptr) # Prints "foo"
print(<object>ptr2) # prints "foo"
The precedence of ``<...>`` is such that ``<type>a.b.c`` is interpreted as ``<type>(a.b.c)``.
Statements and expressions
==========================
......
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