WebAssembly image dithering example

Radu void at null.pt
Fri Aug 3 09:53:08 UTC 2018


On Friday, 3 August 2018 at 09:40:30 UTC, Kagamin wrote:
> Looks like wasm module is sandboxed, so you should marshal 
> anything non-trivial. You can return string pointer (ptr 
> member) and store length in an exported global variable. If the 
> caller reads the stored length right upon receiving the return 
> value, it should be fine.

How you pass strings from wasm to js

```wasm.d
extern(C):

void _log(immutable(char)*, size_t);

void log(string msg)
{
     _log(msg.ptr, msg.length);
}

void echo()
{
     log("Helo from WASM!");
}
```

```wasm.js
const request = new XMLHttpRequest();
request.open('GET', 'wasm.wasm');
request.responseType = 'arraybuffer';
request.onload = () => {
   const wasmCode = request.response;
   const importObject = {
       env: {
         _log: (ptr, len) =>
         {
             try
             {
                 var buffer = new Uint8Array(linearMemory.buffer, 
ptr, len);
                 var msg = '';
                 for (var i=0; i < buffer.length; i++) {
                   msg += String.fromCharCode(buffer[i]);
                 }
                 console.log(msg);
             }
             catch(err)
             {
               console.log(err);
             }
         }
       }
     };
     var wasmModule = new WebAssembly.Module(wasmCode);
     var wasmInstance = new WebAssembly.Instance(wasmModule, 
importObject);
     // obtain the module memory
     var linearMemory= wasmInstance.exports.memory;
     wasmInstance.exports.echo();
};
request.send();
```



More information about the digitalmars-d-ldc mailing list