In [1]:
%load_ext cython
In [2]:
%%cython
# General purpose pointer - no type given
cdef void* p
# Oh hey, let's save the address to an int
cdef int x = 123
p = &x
# How to use the void pointer? You need casting:
cdef int* px = <int*>p
print(px[0])
# Can also SAME POINTER for a double
cdef double y = 0.1
p = &y
# And out again
cdef double* py = <double*>p
print(py[0])
In [3]:
%%cython
x = ['a', 'b', 'c']
cdef void* p = <void*>x # Get a void pointer to the Python object
# Surprise! The memory address is the same as the object id()
print(<long>p)
print(id(x))
# By type-casting to <object>, you can get the original
# Python object back
print(<object>p)
In [4]:
%%cython
# Sometimes "unsigned long long" is too much to type
# Let's rather call it "uint64"
ctypedef unsigned long long uint64
# Now functions are easier to write
cdef uint64 f(uint64 x):
return x // 2
print(f(2**16))
In [5]:
%%cython
# Original function
cdef double f(int x):
return x / 10.0
# "Type" of the function
ctypedef double(*function_type)(int)
# Declare new function pointer
cdef function_type x
x = &f # x now points at function f
# Test it out
print(x(2))
In [ ]: