Home > front end >  Storing unsafe C derivative of temporary Python reference Cython
Storing unsafe C derivative of temporary Python reference Cython

Time:03-28

Although I few similar questions already being asked, but I couldn't get head around on how to fix.

Basically I have this function:

Module one.pyx:

cdef char *isInData(data, dataLength):
    cdef char *ret = <char *>malloc(200)
    memset(ret, 0x00, 200)

    if (b"Hello" in data and b"World" in data):
        strcat(ret, b"Hello World!")

return ret

Module two.pyx:

import one
from libc.stdlib cimport malloc,realloc, free

cdef char *tempo():
    cdef char *str
    str = one.isInData(b"Hello what is up World", 23)

    # do some stuff
    free(str)

Issue occurs on line str = one.isInData("Hello what is up World", 23), I am assuming that as soon as isInData->ret is assigned to str. isInData->ret is deleted which causes this issue. But annyone help me on how to fix this?

CodePudding user response:

import one

This line does a Python import of one. It doesn't know about any cdef functions defined in one (or even that one is a Cython module...). Therefore it assumes that isInData is a Python object that it can look up and that it'll be a callable returning another Python object.

cdf char* str = some_python_function() is unsafe because str points into the Python object. However the Python object is only a temporary and is most likely freed almost immediately.

What you mean is:

cimport one

which tells Cython that it's a Cython module that you're importing, and it should expect to find the declarations at compile-time. You'll probably need to write a pxd file to give the declarations.


I haven't looked in detail at the rest of your code so don't know if you are handling C strings right. But in general you may find it easier just to use Python strings rather than messing around with C string handling.

  • Related