Skip to content

Call functions with params || Creat WebAssembly with extern "c"  #861

@chrisber

Description

@chrisber

My intend is to execute the following functions:

    int counter = 100;

    int count() {
        return counter += 1;
    }

    int add(int a, int b){
        return a + b;
    }

I followed this tutorial
and create a docker container for the webassembly toolchain which allows me to build a *.wasm from *.c with the following command:
docker run --rm --name generate-wasm-default -v ${PWD}:/src -i -t chrisber/llvm-webassembly:latest /bin/build.sh hello_world.c
Basically it does the following:

clang -emit-llvm --target=wasm32 -S hello_world.c
llc hello_world.ll -march=wasm32
s2wasm hello_world.s > hello_world.wast
wast2wasm -o hello_world.wasm hello_world.wast

Then calling within index.js:

const dependencies = {
    "global": {},
    "env": {}
};
const instance = new WebAssembly.Instance(module, dependencies);
const wasm = instance.exports;

Calling the function count:
console.log("count function result is : " + wasm.count()); works just fine, but calling:
console.log("add function result is : " + wasm.add(1,1)); leads to the following error:

Uncaught (in promise) RuntimeError: memory access out of bounds
    at  (<WASM>[1]+15)
    at http://localhost:3000/main.bundle.js:39:60
(anonymous) @ wasm-9d2fd5a6-1:9
(anonymous) @ index.ts:20

My higher goal would be to call functions linked from a shared library like:.

clang -emit-llvm --target=wasm32 -S hello_world.c -L. -lxyz and calling it with

extern "C" {
    //....
}

but the error Uncaught (in promise) RuntimeError: memory access out of bounds prevents me from
experimenting with extern "c".

The project is located here.

I'm stuck with this issue and your help is highly appreciated.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions