I am new to Cython and have very little experience with C so bear with me.
I want to store a fixed-size sequence of immutable byte objects. The object would look like:
obj = (b'abc', b'1234', b'^&$#%')
The elements in the tuple are immutable, but their length is arbitrary.
What I tried was something along the lines of:
cdef char[3] *obj
cdef char* a, b, c
a = b'abc'
b = b'1234'
c = b'^&$#%'
obj = (a, b, c)
But I get:
Storing unsafe C derivative of temporary Python reference
Can someone please point me in the right direction?
Bonus question: how do I type an arbitrarily long sequence of those 3-tuples?
Thanks!
You are definitely close! There appears to be two issues.
First, we need to change the declaration of
obj
so that it reads that we are trying to create an array ofchar*
objects, fixed to a size of 3. To do this, you need to put the type, then the variable name, and only then the size of the array. This will give you the desired array ofchar*
on the stack.Second, when you declare
char* a, b, c
, onlya
is achar*
, whileb
andc
are justchar
! This is made clear in cython during the compilation phase, which outputs the following warning for me:So you should do this instead:
As a side note, you can minimize typing
cdef
by doing this for your code:Bonus:
Based on your level of experience with C and pointers in general, I think I will just show the more newbie-friendly approach using C++ data structures. C++ has simple built-in data structures like
vector
, which is the equivalent of a python list. The C alternative would be to have a pointer to a struct, signifying an "array" oftriplets
. You would then be personally in charge of managing the memory of this using functions likemalloc
,free
,realloc
, etc.Here is something to get you started; I strongly suggest you follow some online C or C++ tutorials on your own and adapt them to cython, which should be fairly trivial after some practice. I am showing both a
test.pyx
file as well as thesetup.py
file that shows how you can compile this with c++ support.test.pyx
setup.py