1 #include <fstream>
2 #include <iostream>
3 #include <sstream>
4 #include <wasmtime.hh>
5
6 using namespace wasmtime;
7
readFile(const char * name)8 std::string readFile(const char *name) {
9 std::ifstream watFile;
10 watFile.open(name);
11 std::stringstream strStream;
12 strStream << watFile.rdbuf();
13 return strStream.str();
14 }
15
main()16 int main() {
17 // First the wasm module needs to be compiled. This is done with a global
18 // "compilation environment" within an `Engine`. Note that engines can be
19 // further configured through `Config` if desired instead of using the
20 // default like this is here.
21 std::cout << "Compiling module\n";
22 Engine engine;
23 auto module =
24 Module::compile(engine, readFile("examples/hello.wat")).unwrap();
25
26 // After a module is compiled we create a `Store` which will contain
27 // instantiated modules and other items like host functions. A Store
28 // contains an arbitrary piece of host information, and we use `MyState`
29 // here.
30 std::cout << "Initializing...\n";
31 Store store(engine);
32
33 // Our wasm module we'll be instantiating requires one imported function.
34 // the function takes no parameters and returns no results. We create a host
35 // implementation of that function here.
36 std::cout << "Creating callback...\n";
37 Func host_func =
38 Func::wrap(store, []() { std::cout << "Calling back...\n"; });
39
40 // Once we've got that all set up we can then move to the instantiation
41 // phase, pairing together a compiled module as well as a set of imports.
42 // Note that this is where the wasm `start` function, if any, would run.
43 std::cout << "Instantiating module...\n";
44 auto instance = Instance::create(store, module, {host_func}).unwrap();
45
46 // Next we poke around a bit to extract the `run` function from the module.
47 std::cout << "Extracting export...\n";
48 auto run = std::get<Func>(*instance.get(store, "run"));
49
50 // And last but not least we can call it!
51 std::cout << "Calling export...\n";
52 run.call(store, {}).unwrap();
53
54 std::cout << "Done\n";
55 }
56