Hi,
Of course the current code can't work, as the typed_memory_view points
to some memory space that will be deleted at end of the fonction (as the
dst vector will be deleted since it is in the stack, regardless of the
std::move(ret) which does not move the vector but the emscripten::val).
The deleted memory space might be re-used later on, explaining why you
have the impression data is "overwritten" during successive calls.
Using "new std::vector" will prevent the memory delete/overwrite issue,
but as you noticed, it is not possible to .delete anything.
The best for your use case would be to create a new class
"TranscodedImage", containing the std::vector dst, and exposed using
Embind. That class will hold responsibility of the vector, and exposing
the class using Embind will allow you to call .delete() on it later on.
Something like (pseudo-code):
class TranscodedImage {
std::vector<uint8_t> dst;
val get_typed_memory_view() {
return typed_memory_view(dst.size(), dst.data())
}
void compute_data( ... ) {
// actually fills 'dst'
}
}
EMSCRIPTEN_BINDINGS( mylib )
{
emscripten::class_<TranscodedImage>( "TranscodedImage" )
.constructor( )
.function( "compute_data", &TranscodedImage::compute_data )
.function( "get_typed_memory_view()",
&TranscodedImage::get_typed_memory_view )
}
// In your javascript code
let trans_img = new Module.TranscodedImage()
trans_img.compute_data(... whatever needed to compute the image ...)
let img_data = trans_img.get_typed_memory_view()
... do whatever needed with img_data. Then, later on, when the data is
no more needed
trans_img.delete(); // will call the TranscodedImage class destructor
=> deletes the vector contents. So, everything is reclaimed in the end
(NB: img_data will no more point to something valid!!)
Note the .delete() call : this is called on the Emscripten-exposed C++ class
Hope this helps a bit,
Cheers,
Gabriel