Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
bytecodealliance
GitHub Repository: bytecodealliance/wasmtime
Path: blob/main/crates/c-api/tests/component/call_func.cc
1692 views
1
#include "utils.h"
2
3
#include <array>
4
#include <gtest/gtest.h>
5
#include <wasmtime.h>
6
7
TEST(component, call_func) {
8
static constexpr auto component_text = std::string_view{
9
R"END(
10
(component
11
(core module $m
12
(func (export "f") (param $x i32) (param $y i32) (result i32)
13
(local.get $x)
14
(local.get $y)
15
(i32.add)
16
)
17
)
18
(core instance $i (instantiate $m))
19
(func $f (param "x" u32) (param "y" u32) (result u32) (canon lift (core func $i "f")))
20
(export "f" (func $f))
21
)
22
)END",
23
};
24
const auto engine = wasm_engine_new();
25
EXPECT_NE(engine, nullptr);
26
27
const auto store = wasmtime_store_new(engine, nullptr, nullptr);
28
const auto context = wasmtime_store_context(store);
29
30
wasmtime_component_t *component = nullptr;
31
32
auto err = wasmtime_component_new(
33
engine, reinterpret_cast<const uint8_t *>(component_text.data()),
34
component_text.size(), &component);
35
36
CHECK_ERR(err);
37
38
const auto f =
39
wasmtime_component_get_export_index(component, nullptr, "f", 1);
40
41
EXPECT_NE(f, nullptr);
42
43
const auto linker = wasmtime_component_linker_new(engine);
44
45
wasmtime_component_instance_t instance = {};
46
err = wasmtime_component_linker_instantiate(linker, context, component,
47
&instance);
48
CHECK_ERR(err);
49
50
wasmtime_component_func_t func = {};
51
const auto found =
52
wasmtime_component_instance_get_func(&instance, context, f, &func);
53
EXPECT_TRUE(found);
54
55
auto params = std::array<wasmtime_component_val_t, 2>{
56
wasmtime_component_val_t{
57
.kind = WASMTIME_COMPONENT_U32,
58
.of = {.u32 = 34},
59
},
60
wasmtime_component_val_t{
61
.kind = WASMTIME_COMPONENT_U32,
62
.of = {.u32 = 35},
63
},
64
};
65
66
auto results = std::array<wasmtime_component_val_t, 1>{};
67
68
err =
69
wasmtime_component_func_call(&func, context, params.data(), params.size(),
70
results.data(), results.size());
71
CHECK_ERR(err);
72
73
err = wasmtime_component_func_post_return(&func, context);
74
CHECK_ERR(err);
75
76
EXPECT_EQ(results[0].kind, WASMTIME_COMPONENT_U32);
77
EXPECT_EQ(results[0].of.u32, 69);
78
79
wasmtime_component_export_index_delete(f);
80
wasmtime_component_linker_delete(linker);
81
82
wasmtime_store_delete(store);
83
wasm_engine_delete(engine);
84
}
85
86