Emscripten malloc and free across JS and C++

我只是一个虾纸丫 提交于 2020-03-01 07:43:25

问题


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?


回答1:


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




回答2:


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 ;
}


来源:https://stackoverflow.com/questions/34050275/emscripten-malloc-and-free-across-js-and-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!