wasm wrap string

C代码

// C - code
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#ifndef EM_PORT_API
    #if defined(__EMSCRIPTEN__)
        #include <emscripten.h>
#if defined(__cplusplus)
#define EM_PORT_API(rettype) extern "C" rettype EMSCRIPTEN_KEEPALIVE
#else
#define EM_PORT_API(rettype) rettype EMSCRIPTEN_KEEPALIVE
#endif
    #else
#if defined(__cplusplus)
#define EM_PORT_API(rettype) extern "C" rettype 
#else
#define EM_PORT_API(rettype) rettype 
#endif
    #endif
#endif

EM_PORT_API(char*) fm_substr(char* buf, int pos) {
    char * ret;
    int sz = strlen(buf);

    ret = calloc(sz+1-pos, 1);
    memcpy(ret, buf+pos, sz-pos);

    return ret;
}

 

编译:

emcc -s RESERVED_FUNCTION_POINTERS=20 -s EXPORTED_RUNTIME_METHODS=['ccall','cwrap','stringToUTF8','UTF8ToString'] -s EXPORTED_FUNCTIONS=['_malloc','_free'] test.c -o test.js

 

 

使用:js代码

// JS - code

var result = Module.ccall('fm_substr', // name of C function
  'string', // return type
  ['string', 'number'], // argument types
  ['abc', 1]); // arguments

var c_js_ds_substr = Module.cwrap('fm_substr', // name of C function
  'string', // return type
  ['string', 'number']); // argument types
// Call c_javascript_add normally

console.log(c_js_ds_substr('abc', 1));
console.log(c_js_ds_substr('abc', 2));