Proper way to initialize memoryview in stack-allocated struct?

361 views
Skip to first unread message

David Vierra

unread,
Jun 29, 2015, 8:11:04 AM6/29/15
to cython...@googlegroups.com
I have defined a struct containing a memoryview. 

```
cdef struct MyStruct:
    unsigned int [:] my_mview
```

I allocate this struct on the stack as a local variable. 

```
cdef void MyFunction():
    cdef MyStruct local_struct
```

When assigning another object (a numpy array, to be precise) I get a C-level crash because my stack-allocated struct is not initialized. Unexpected - I should be able to overwrite an uninitialized struct however I want.

```
    local_struct.my_mview = numpy.arange(20)  /* ACCESS_VIOLATION */
```

The crash occurs inside the _PYX_XDEC_MEMVIEW, which does so reasonably as it is given an uninitialized __Pyx_memoryviewslice. I noted that when I declare a memoryview as a local variable, C code is generated that initializes the variable with something like `{ 0, 0, { 0 }, { 0 }, { 0 } }`, filling in the fields of the __Pyx_memoryviewslice. However, when I define my own struct containing a memoryview, and declare the struct as a local variable, no initialization code is generated for the struct's member.

What is the best way to initialize the struct as a local variable? I found I can write `local_struct.my_mview = None` (or even local_struct = [None, None, None] if it has several memoryviews in it), but would it be better to `memzero` the entire struct? Or do something else?

David Vierra

unread,
Jun 29, 2015, 8:17:46 AM6/29/15
to cython...@googlegroups.com
I made a mistake in my description. I cannot write `local_struct.my_mview = None`; what I found I had to do was initialize the struct as it is declared:
```
    cdef MyStruct local_struct = [None]
```

Marc-Alexandre Côté

unread,
Nov 6, 2015, 8:50:28 PM11/6/15
to cython-users
I had a similar problem with dynamically allocating a structure containing a memview.

You made me realize to use calloc instead of malloc. So, 'memzero' the entire struct was the way to go for me.

Thanks man
Reply all
Reply to author
Forward
0 new messages