Is there an alternative to the following syntax of accessing a
pointer's value:
cdef int i = 10
cdef int* ptr = &i
ptr[0] = 5 # value of i becomes 5
# *ptr = 5 # does not work
print(ptr[0])
The array indexing syntax becomes a bit tedious after a while,
especially when I need to modify hundreds of pointer values.
No.
Dag Sverre
On Jan 8, 5:05 pm, Dag Sverre Seljebotn <da...@student.matnat.uio.no>
wrote:
In the .pyx file, I have a pointer to a C struct. I need to access the
contents of the struct.
From within the .pyx file, I have tried:
#1
cdef mystruct_t c_struct = <mystruct_t> *(<mystruct_t *> p_c_struct)
which gives the error "Expected an identifier or literal"
#2
I have also tried:
pythonObj.a = p_c_struct->structField
which also gives the error "Expected an identifier or literal"
#3
I have considered pointer arithmetic but mystruct_t contains a union.
What is the proper way to do this?
One thing to mention is that my p_c_struct is actually a Python int
type that I cast into a pointer on the way in.
Thanks in advance!
Cass
To elaborate, Python already has meaning attached to the prefix *
operator (packing tuples). The index notation gets annoying, but
writing Cython is (or at least should be) more like writing Python
than writing C.
- Robert
Try
cdef mystruct_t c_struct = p_c_struct[0] # assuming p_c_struct is
of type mystruct_t*
cdef mystruct_t c_struct = (<mystruct_t *>p_c_struct)[0] # otherwise
> #2
> I have also tried:
> pythonObj.a = p_c_struct->structField
> which also gives the error "Expected an identifier or literal"
Cython automatically dereferences for you, just use
p_c_struct.structField
-> is illegal Python/Cython syntax.
> #3
> I have considered pointer arithmetic but mystruct_t contains a union.
>
> What is the proper way to do this?
>
> One thing to mention is that my p_c_struct is actually a Python int
> type that I cast into a pointer on the way in.
Sounds dangerous, but can work. Make sure you cast it to a (large
enough) C int, then a pointer.
- Robert