Skip to content

Instantly share code, notes, and snippets.

@floooh
Last active November 16, 2021 16:30
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save floooh/50a441a9422ab6caa18d8703b59630c1 to your computer and use it in GitHub Desktop.
Save floooh/50a441a9422ab6caa18d8703b59630c1 to your computer and use it in GitHub Desktop.
WASM in VSCode Extension
import * as vscode from 'vscode';
import {promises as fs} from 'fs';
import * as path from 'path';
export function activate(context: vscode.ExtensionContext) {
context.subscriptions.push(vscode.commands.registerCommand('wasmtest.helloWorld', async () => {
const wasm = await load_wasm(path.join(context.extensionPath, 'media', 'bla.wasm'));
const exports: any = wasm.exports; // not sure how static typing is supposed to work here
const c_str = exports.greeting();
const js_str = c_to_js_string(c_str, exports.memory.buffer);
vscode.window.showInformationMessage("From WASM: " + js_str);
}));
}
async function load_wasm(wasm_path: string): Promise<WebAssembly.Instance> {
const wasm_bytes = new Uint8Array(await fs.readFile(wasm_path));
const wasm = await WebAssembly.instantiate(wasm_bytes, {});
return wasm.instance;
}
function c_to_js_string(c_str: number, mem: ArrayBuffer): string {
const bytes = new Uint8Array(mem, c_str);
let str = "";
for (let i = 0; bytes[i]; i++) {
str += String.fromCharCode(bytes[i]);
}
return str;
}
export function deactivate() {}
import * as vscode from 'vscode';
import * as fs from 'fs';
import * as path from 'path';
declare const WebAssembly: any;
export function activate(context: vscode.ExtensionContext) {
context.subscriptions.push(vscode.commands.registerCommand('wasmtest.helloWorld', () => {
const wasm_path = path.join(context.extensionPath, 'media', 'bla.wasm');
fs.readFile(wasm_path, (err, data) => {
if (!err) {
const buf = new Uint8Array(data);
WebAssembly.instantiate(buf, {}).then((result: any) => {
const instance = result.instance;
const exports = instance.exports;
const res = exports.greeting();
const res_ptr = new Uint8Array(exports.memory.buffer, res);
let str = "";
for (let ii = 0; res_ptr[ii]; ii++) {
str += String.fromCharCode(res_ptr[ii]);
}
vscode.window.showInformationMessage("From WASM: " + str);
});
}
});
}));
}
export function deactivate() {}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment