Michael WS Michael WS - 22 days ago 6
C++ Question

cython create string with nogil

I would like to create a c++ string in a nogil function in a file that would be cimported via pxd. If I define, string output = "" or string output = string("blah"), this uses the python interpreter. Is there a way to define the a string so that the compiler writes in the cython cpp file:

std::string val = "blah";


Basically have this:

from libcpp.string cimport string
cdef string my_func() nogil:
cdef:
string output = "blah"
....
return output

Answer
%%cython -a

#distutils: language = c++

from libcpp.string cimport string

cdef string my_func() nogil:
    cdef:
        char* c_str = 'blah'
        string output = <string>(c_str)
    return output


def py_call():
    return my_func()

Then calling py_call() gives b'blah', i.e. a bytes object.