frang75 / nappgui_src

SDK for building cross-platform desktop apps in ANSI-C
https://www.nappgui.com
MIT License
442 stars 43 forks source link

Problem with streams in core #132

Open pb-lime opened 1 month ago

pb-lime commented 1 month ago

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;
}
frang75 commented 1 month ago

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

SamSandq commented 4 weeks ago

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).