String buffer to be filled by native side

Several places in the httpd expect that the user first requests a length and then provides a char * buffer with matching space.

I would like to provide a bytearray or similar as the buffer. But MP expects a string when the parameter was a char *.

My current solution looks like this:

def get_header_value(req, name):
    blen = req.get_hdr_value_len(name);
    if not blen: return None
    buffer = " "*blen         # allocate a string as buffer incl. space for \0
    req.get_hdr_value_str(name, buffer, blen+1);
    return buffer;

I am not sure if this is a safe solution. Are python string buffers always 0 terminated char arrays internally so that " "*32 is actually 33 bytes? Can I just overwrite them?

In Python, “string” in an immutable container, so in principle we are not supposed to change it.
Practically, this would probably still work because in Micropython strings are represented internally as C string (when not interned).

I recommend you pass bytes instead of string, to make things clearer, although bytes is still an immutable container. It’s also cleaner to initialize a buffer as bytes(len) instead of building a string of spaces.

If you really want to be on the safe side, create a wrapper that receives void * instead of char *, and pass to it a bytearray or memoryview.

If this turns up to be a problem, I could check if I can change the binding script to also accept bytearray/memoryview when handling strings.

Thanks. Yes, indeed, bytes is a much better choice and would even work with encodings different than the MP internal one.

I’ve added the capability to pass bytearray/memoryview in places where string (char *) is expected.

Works as advertised! Thanks a lot. Being able to pass something mutable definitely makes things nicer.