xref: /wasmtime-44.0.1/examples/linking.cc (revision 13ebd6f5)
1 #include <fstream>
2 #include <iostream>
3 #include <sstream>
4 #include <wasmtime.hh>
5 
6 using namespace wasmtime;
7 
unwrap(Result<T,E> result)8 template <typename T, typename E> T unwrap(Result<T, E> result) {
9   if (result) {
10     return result.ok();
11   }
12   std::cerr << "error: " << result.err().message() << "\n";
13   std::abort();
14 }
15 
readFile(const char * name)16 std::string readFile(const char *name) {
17   std::ifstream watFile;
18   watFile.open(name);
19   std::stringstream strStream;
20   strStream << watFile.rdbuf();
21   return strStream.str();
22 }
23 
main()24 int main() {
25   Engine engine;
26   Store store(engine);
27 
28   // Read our input `*.wat` files into `std::string`s
29   std::string linking1_wat = readFile("examples/linking1.wat");
30   std::string linking2_wat = readFile("examples/linking2.wat");
31 
32   // Compile our two modules
33   Module linking1_module = Module::compile(engine, linking1_wat).unwrap();
34   Module linking2_module = Module::compile(engine, linking2_wat).unwrap();
35 
36   // Configure WASI and store it within our `wasmtime_store_t`
37   WasiConfig wasi;
38   wasi.inherit_argv();
39   wasi.inherit_env();
40   wasi.inherit_stdin();
41   wasi.inherit_stdout();
42   wasi.inherit_stderr();
43   store.context().set_wasi(std::move(wasi)).unwrap();
44 
45   // Create our linker which will be linking our modules together, and then add
46   // our WASI instance to it.
47   Linker linker(engine);
48   linker.define_wasi().unwrap();
49 
50   // Instantiate our first module which only uses WASI, then register that
51   // instance with the linker since the next linking will use it.
52   Instance linking2 = linker.instantiate(store, linking2_module).unwrap();
53   linker.define_instance(store, "linking2", linking2).unwrap();
54 
55   // And with that we can perform the final link and the execute the module.
56   Instance linking1 = linker.instantiate(store, linking1_module).unwrap();
57   Func f = std::get<Func>(*linking1.get(store, "run"));
58   f.call(store, {}).unwrap();
59 }
60