Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
bytecodealliance
GitHub Repository: bytecodealliance/wasmtime
Path: blob/main/examples/fuel.cc
1685 views
1
/*
2
Example of instantiating of the WebAssembly module and invoking its exported
3
function.
4
5
You can compile and run this example on Linux with:
6
7
cargo build --release -p wasmtime-c-api
8
c++ examples/fuel.cc -std=c++20 \
9
-I crates/c-api/include \
10
-I crates/c-api/wasm-c-api/include \
11
target/release/libwasmtime.a \
12
-lpthread -ldl -lm \
13
-o fuel
14
./fuel
15
16
Note that on Windows and macOS the command will be similar, but you'll need
17
to tweak the `-lpthread` and such annotations.
18
*/
19
20
#include <fstream>
21
#include <iostream>
22
#include <sstream>
23
#include <wasmtime.hh>
24
25
using namespace wasmtime;
26
27
std::string readFile(const char *name) {
28
std::ifstream watFile;
29
watFile.open(name);
30
std::stringstream strStream;
31
strStream << watFile.rdbuf();
32
return strStream.str();
33
}
34
35
const size_t kStoreFuel = 10000;
36
37
int main() {
38
Config config;
39
config.consume_fuel(true);
40
Engine engine(std::move(config));
41
Store store(engine);
42
store.context().set_fuel(kStoreFuel).unwrap();
43
44
auto wat = readFile("examples/fuel.wat");
45
Module module = Module::compile(engine, wat).unwrap();
46
Instance instance = Instance::create(store, module, {}).unwrap();
47
Func fib = std::get<Func>(*instance.get(store, "fibonacci"));
48
49
// Call it repeatedly until it fails
50
for (int32_t n = 1;; n++) {
51
auto result = fib.call(store, {n});
52
if (!result) {
53
std::cout << "Exhausted fuel computing fib(" << n << ")\n";
54
break;
55
}
56
uint64_t consumed = kStoreFuel - store.context().get_fuel().unwrap();
57
auto fib_result = std::move(result).unwrap()[0].i32();
58
59
std::cout << "fib(" << n << ") = " << fib_result << " [consumed "
60
<< consumed << " fuel]\n";
61
store.context().set_fuel(kStoreFuel).unwrap();
62
}
63
}
64
65