frang75/nappgui_src

Problem with streams in core

Opened this issue · 2 comments

Foremost, many thanks for your wonderful work (Libraries and Documentation). I will try to use it in a "commandline app" and have a problem with streams.
After reading 2 strings from the stream, both strings have the same value. Is this an issue, or am I the problem?
Here is an example:

static Product product_read(Stream* stm)
{
    Product product;
    product.name = stm_read_chars(stm, namelen);
    //Here we print product.name and everything seems to be fine
    bstd_printf("Product: %s\n", product.name);
    product.description = stm_read_chars(stm, desclen);
    //Now product.name and product.description have the same value, the value of description.
    bstd_printf("Product: %s, Description: %s\n", product.name, product.description);
    return product;
}

Hi @pb-lime!

I suspect that your struct has this form:

struct Product
{
     const char_t *name;
     const char_t *description;
     ...
}

the pointer returned by stm_read_chars() is temporal. You have to make a string copy to preserve.
https://nappgui.com/en/core/stream.html#f52

I recommend you take a look at this serialization section.
https://nappgui.com/en/core/arrst.html#h6

There might be a problem in streams. I use (per Francisco's earlier suggestion) the following code to generate PNG thumbnail images for my photos on import:

    Stream *stm = stm_memory(100000);   // Memory stream where the encoded image will be written, falls over if too small
    image_codec(img, ekPNG);          // Set the codec you want
    image_write(stm, img);            // Write an encoded version of the image
    *size = stm_buffer_size(stm); // The size of your PNG
    const byte_t *data = stm_buffer(stm); // The PNG data
    stm_close(&stm);

Originally Francisco suggested a size of 2000, with the remark that it will grow if needed. However, in practice this does not always work; the image is sometimes not a valid PNG (no idea what it is, but it cannot be displayed; not NULL however). A much larger size, like 100000 here is required for it never to fail (at least not so far).