Reputation: 1
Suppose I allocate some memory M in Javascript via Emscripten _malloc
(Javascript). Am I allowed to pass ownership of M into a marshaled C++ function that calls free
(C++) on it?
Upvotes: 5
Views: 6961
Reputation:
take a look at this code , this is a piece of source code in library.js about emscripten
free: function() {
#if ASSERTIONS == 2
Runtime.warnOnce('using stub free (reference it from C to have the real one included)');
#endif
},
as you saw free is not implemented but you can free with exampe below
char *s1 = (char*) malloc ( 256 );
EM_ASM_INT ( {
return _free ( $0 );
}, s1 ) ;
at the moment works in this way this is a full example
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <emscripten.h>
int main ( void )
{
// ************************************** free do not free
char *s1 = (char*) malloc ( 256 );
strcpy ( s1,"Hello\0" ) ;
puts (s1);
free(s1);
puts(s1);
// ************************************** free do not free
char *s2 = (char* )EM_ASM_INT ( {
var p = Module._malloc(256);
setValue ( p + 0 , 65 , 'i8' ) ; // A
setValue ( p + 1 , 66 , 'i8' ) ; // B
setValue ( p + 2 , 67 , 'i8' ) ; // C
setValue ( p + 3 , 0 , 'i8' ) ;
return p ;
} , NULL );
puts(s2);
free(s2); // do not free
puts(s2);
// ************************************** _free do free
/*
EM_ASM_INT ( {
return _free ( $0 );
}, s1 ) ;
EM_ASM_INT ( {
return _free ( $0 );
}, s1 ) ;
*/
puts(s1);
puts(s2);
char * s3 = (char*) EM_ASM_INT ( {
var str = 'ciao' ;
var ret = allocate(intArrayFromString(str), 'i8', ALLOC_NORMAL);
return ret ;
}, NULL ) ;
puts( s3 ) ;
free(s3); // do not free
puts( s3 ) ;
// ************************************** _free do free
/*
EM_ASM_INT ( {
return _free ( $0 );
}, s3 ) ;
*/
puts( s3 ) ;
return 0 ;
}
Upvotes: -1
Reputation: 2006
Yes. In Emscripten, the C++ version of malloc is converted to Module._malloc() in JavaScript; likewise Module._free() is the same as C++'s free().
Upvotes: 9