[英]Emscripten malloc and free across JS and C++
Suppose I allocate some memory M in Javascript via Emscripten _malloc
(Javascript). 假设我通过Emscripten
_malloc
(Javascript)在Javascript中分配一些内存M. Am I allowed to pass ownership of M into a marshaled C++ function that calls free
(C++) on it? 我是否允许将M的所有权传递给一个调用
free
(C ++)的封送C ++函数?
Yes. 是。 In Emscripten, the C++ version of malloc is converted to Module._malloc() in JavaScript;
在Emscripten中,malloc的C ++版本在JavaScript中转换为Module._malloc(); likewise Module._free() is the same as C++'s free().
同样,Module._free()与C ++的free()相同。
take a look at this code , this is a piece of source code in library.js about emscripten 看看这段代码,这是关于emscripten的library.js中的一段源代码
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 ;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.