I would like to test WebAssembly for doing some complex array calculations.
So I've written a simple C++ function adding two int
arrays containing 3 elements each :
// hello.cpp
extern "C" {
void array_add(int * summed, int* a, int* b) {
for (int i=0; i < 3; i++) {
summed[i] = a[i] + b[i];
}
}
}
And compiled this with :
emcc hello.cpp -s WASM=1 -s "MODULARIZE=1" -s "EXPORT_NAME='HELLO'" -s "BINARYEN_METHOD='native-wasm'" -s "EXPORTED_FUNCTIONS=['_array_add']" -o build/hello.js
Which generates among others, a js
and a wasm
file. I load these with the following html page :
<!doctype html>
<html lang="en-us">
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript" src="build/hello.js"></script>
<script type="text/javascript">
function reqListener () {
// Loading wasm module
var arrayBuffer = oReq.response
HELLO['wasmBinary'] = arrayBuffer
hello = HELLO({ wasmBinary: HELLO.wasmBinary })
// Calling function
var result = new Int32Array(3)
var a = new Int32Array([1, 2, 3])
var b = new Int32Array([4, 5, 2])
hello._array_add(result, a, b)
console.log('result', result)
}
var oReq = new XMLHttpRequest();
oReq.responseType = "arraybuffer";
oReq.addEventListener("load", reqListener);
oReq.open("GET", "build/hello.wasm");
oReq.send();
</script>
</head>
<body>
</body>
</html>
But somehow, the result
array is always [0, 0, 0]
.
I have tried a variety of things, including calling the function with ccall()
(see emscripten docs ) and it seems that I cannot get an array passed as argument of my wasm compiled function.
For example, with the following C++ function :
extern "C" {
int first(int * arr) {
return arr[0];
}
}
Result when called in JavaScript is a random-ish integer, instead of the expected value from the array I passed as argument.
What am I missing?
NB : I know pretty much nothing about C++, so all apologies if this is a beginner question related to my C++ ignorance ...
See Question&Answers more detail:os