1 /*
2 An example of how to interact with multiple memories.
3 
4 You can build the example using CMake:
5 
6 mkdir build && (cd build && cmake .. && \
7   cmake --build . --target wasmtime-multimemory-cpp)
8 
9 And then run it:
10 
11 build/wasmtime-multimemory-cpp
12 */
13 
14 #include <fstream>
15 #include <iostream>
16 #include <sstream>
17 #include <wasmtime.hh>
18 
19 using namespace wasmtime;
20 
readFile(const char * name)21 std::string readFile(const char *name) {
22   std::ifstream watFile;
23   watFile.open(name);
24   std::stringstream strStream;
25   strStream << watFile.rdbuf();
26   return strStream.str();
27 }
28 
main()29 int main() {
30   std::cout << "Initializing...\n";
31   Config config;
32   config.wasm_multi_memory(true);
33   Engine engine(std::move(config));
34   Store store(engine);
35 
36   std::cout << "Compiling module...\n";
37   auto wat = readFile("examples/multimemory.wat");
38   Module module = Module::compile(engine, wat).unwrap();
39 
40   std::cout << "Instantiating module...\n";
41   Instance instance = Instance::create(store, module, {}).unwrap();
42   Memory memory0 = std::get<Memory>(*instance.get(store, "memory0"));
43   Memory memory1 = std::get<Memory>(*instance.get(store, "memory1"));
44 
45   std::cout << "Checking memory...\n";
46   // (Details intentionally omitted to mirror Rust example concise output.)
47 
48   std::cout << "Mutating memory...\n";
49   auto d0 = memory0.data(store);
50   if (d0.size() >= 0x1004)
51     d0[0x1003] = 5;
52   auto d1 = memory1.data(store);
53   if (d1.size() >= 0x1004)
54     d1[0x1003] = 7;
55 
56   std::cout << "Growing memory...\n";
57   memory0.grow(store, 1).unwrap();
58   memory1.grow(store, 2).unwrap();
59 
60   return 0;
61 }
62