We Write a function that converts a string to lowercase in WebAssembly, demonstrating how to set the input string from Jav Ascript.
WASM Fiddle:https://wasdk.github.io/wasmfiddle/?h1s69
Demo Repo:https://github.com/guybedford/wasm-intro
We want to create a funcrtion ' toLowerCase ', which enable JS-to-write in Memory.
To write the data into WASM, we need to variables in C code, one was ' inStr ' which get original input (for example ' Hello world '), another is ' outstr ' which would transform to lower case string (for example: ' Hello World ').
C Code:
voidConsoleLog (Char* Offset,intlen);Charinstr[ -];Charoutstr[ -];Char*Getinstroffset () {return&instr[0];}voidtoLowerCase () { for(inti =0; I < -; i++ ) { Charc =Instr[i]; if(C > -&& C < the) {C= C + +; } Outstr[i]=C; } consolelog (&outstr[0], -);}
Js:some code to get wasm instance.
var New Webassembly.module (wasmcode); var New webassembly.instance (wasmmodule, { env: { consolelog (offset, len) { new Uint8array (Mem.buffer, offset, len); Log (new Textdecoder (). Decode (STRBUF)); } = WasmInstance.exports.memory;
Now we need to write data from JS to WASM memory, the "the" to does it is just to put data into ' inStr ':
Const MEM = wasmInstance.exports.memory; function writestring (str, offset) { new Textencoder (). Encode (str); New Uint8array (Mem.buffer, offset, strbuf.length); for (Let i = 0; i < strbuf.length; i++) { = strbuf[i];}} } WriteString (' Hello Web Assembly ', WasmInstance.exports.getInStrOffset ());
Because What ' wasmInstance.exports.getInStrOffset () ' Return us was the first char address of ' inStr ', then we use for loop To write data into ' inStr '.
After writting the data and then we can call ' toLowerCase ' to see the result:
varWasmmodule =NewWebassembly.module (wasmcode);varWasminstance =Newwebassembly.instance (Wasmmodule, {env: {ConsoleLog (offset, len) {const STRBUF=NewUint8array (Mem.buffer, offset, Len); Log (NewTextdecoder (). Decode (STRBUF)); }}); const MEM=wasmInstance.exports.memory;functionwritestring (str, offset) {const STRBUF=NewTextencoder (). Encode (str); Const OUTBUF=NewUint8array (Mem.buffer, offset, strbuf.length); for(Let i = 0; i < strbuf.length; i++) {Outbuf[i]=Strbuf[i]; }}}writestring (' Hello Web Assembly ', WasmInstance.exports.getInStrOffset ()); WasmInstance.exports.toLowerCase ();
[WASM] Write to WebAssembly Memory from JavaScript