File: casting_python.py

package info (click to toggle)
cython 3.0.11%2Bdfsg-2
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 19,092 kB
  • sloc: python: 83,539; ansic: 18,831; cpp: 1,402; xml: 1,031; javascript: 511; makefile: 403; sh: 204; sed: 11
file content (22 lines) | stat: -rw-r--r-- 858 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
from cython.cimports.cpython.ref import PyObject

def main():

    python_string = "foo"

    # Note that the variables below are automatically inferred
    # as the correct pointer type that is assigned to them.
    # They do not need to be typed explicitly.

    ptr = cython.cast(cython.p_void, python_string)
    adress_in_c = cython.cast(Py_intptr_t, ptr)
    address_from_void = adress_in_c        # address_from_void is a python int

    ptr2 = cython.cast(cython.pointer(PyObject), python_string)
    address_in_c2 = cython.cast(Py_intptr_t, 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(cython.cast(object, ptr))                     # Prints "foo"
    print(cython.cast(object, ptr2))                    # prints "foo"