index. js
'use strict';
import fs from 'fs';
const bin = fs.readFileSync('test.wasm');
// only checks for primes up to 100
const primeAppBin = new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0, 1, 10, 2, 96, 0, 1, 127, 96, 1, 127, 1, 127, 3, 3, 2, 1, 0, 5, 4, 1, 1, 1, 1, 7, 32, 3, 6, 109, 101, 109, 111, 114, 121, 2, 0, 7, 105, 115, 80, 114, 105, 109, 101, 0, 0, 9, 103, 101, 116, 80, 114, 105, 109, 101, 115, 0, 1, 10, 142, 1, 2, 61, 1, 2, 127, 65, 1, 33, 1, 32, 0, 65, 4, 78, 4, 127, 32, 0, 65, 127, 106, 33, 2, 65, 2, 33, 1, 2, 64, 3, 64, 32, 0, 32, 1, 111, 69, 13, 1, 32, 1, 65, 1, 106, 34, 1, 32, 2, 71, 13, 0, 11, 65, 1, 15, 11, 65, 0, 5, 65, 1, 11, 11, 78, 1, 4, 127, 65, 2, 33, 0, 3, 64, 2, 64, 32, 0, 65, 4, 79, 4, 64, 32, 0, 65, 127, 106, 33, 3, 65, 2, 33, 2, 3, 64, 32, 0, 32, 2, 112, 69, 13, 2, 32, 2, 65, 1, 106, 34, 2, 32, 3, 71, 13, 0, 11, 11, 32, 1, 65, 1, 106, 33, 1, 11, 32, 0, 65, 1, 106, 34, 0, 65, 228, 0, 71, 13, 0, 11, 32, 1, 11, 11, 9, 1, 0, 65, 128, 12, 11, 2, 160, 6]);
(async () => {
let buff;
const imports = {
env: {
execWasm: (byteOffset, length) => {
WebAssembly.instantiate(new Uint8Array(buff, byteOffset, length)).then(app => console.log(app.instance.exports.getPrimes() + ' primes found'));
}
}
};
const app = await WebAssembly.instantiate(bin, imports);
const { memory, test } = app.instance.exports;
const view = new Uint8Array(memory.buffer, 0, primeAppBin.length);
for (let i in view) view[i] = primeAppBin[i];
buff = memory.buffer;
test(view.byteOffset, view.byteLength);
})();
test. cpp
// emcc -O3 "test.cpp" -o "test.wasm" -s STANDALONE_WASM -s EXPORTED_FUNCTIONS="['_test']" -s ERROR_ON_UNDEFINED_SYMBOLS=0 -Wl,--no-entry -msimd128 -s INITIAL_MEMORY=64kb -s ALLOW_MEMORY_GROWTH=0 -s TOTAL_STACK=0kb
#include <emscripten.h>
extern "C" {
extern void execWasm(int byteOffset, int length);
EMSCRIPTEN_KEEPALIVE
void test (int byteOffset, int length) {
execWasm(byteOffset, length);
}
}
простых чисел. cpp
// emcc -O3 "primes.cpp" -o "primes.wasm" -s STANDALONE_WASM -s EXPORTED_FUNCTIONS="['_getPrimes']" -s ERROR_ON_UNDEFINED_SYMBOLS=0 -Wl,--no-entry -msimd128 -s INITIAL_MEMORY=64kb -s ALLOW_MEMORY_GROWTH=0 -s TOTAL_STACK=0kb
extern "C" {
bool isPrime(int n) {
for (int i = 2; i < n - 1; i++) {
if (n % i == 0)
return false;
}
return true;
}
int getPrimes() {
int primesFound = 0;
for (int i = 2; i < 4'206'969; i++) {
if (isPrime(i)) {
primesFound++;
}
}
return primesFound;
}
}