Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create empty char arrays in Cython without loops

Tags:

python

c

cython

Well, this seems easy, but I can't find a single reference on the web. In C we can create a char array of n null-characters as follows:

char arr[n] = "";

But when I try to do the same in Cython with

cdef char arr[n] = ""

I get this compilation error:

Error compiling Cython file:
------------------------------------------------------------
...
cdef char a[n] = ""
                   ^
------------------------------------------------------------

Syntax error in C variable declaration

Obviously Cython doesn't allow to declare arrays this way, but is there an alternative? I don't want to manually set each item in the array, that is I'm not looking for something like this

cdef char a[10]
for i in range(0, 10, 1):
    a[i] = b"\0"
like image 897
Eli Korvigo Avatar asked May 29 '15 14:05

Eli Korvigo


1 Answers

You don't have to set each element to make a length-zero C string. It is sufficient to just zero the first element:

cdef char arr[n]
arr[0] = 0

Next, if you want to zero the whole char array, use memset

from libc.string cimport memset
cdef char arr[n]
memset(arr, 0, n)

And if C purists complain about the 0 instead of '\0', note that the '\0' is a Python string (unicode in Python 3) in Cython. '\0' is not a C char in Cython! memset expects an integer value for its second argument, not a Python string.

If you really want to know the int value of a C '\0' in Cython, you must write a helper function in C:

/* zerochar.h */
static int zerochar() 
{
    return '\0';
}

And now:

cdef extern from "zerochar.h":
    int zerochar()

cdef char arr[n]
arr[0] = zerochar()

or

cdef extern from "zerochar.h":
    int zerochar()

from libc.string cimport memset
cdef char arr[n]
memset(arr, zerochar(), n)
like image 96
Sturla Molden Avatar answered Sep 24 '22 23:09

Sturla Molden