1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
|
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include "wasm_export.h"
#define P_CHECK(x, name) \
if (!(x)) { \
perror(name); \
return EXIT_FAILURE; \
}
#define WAMR_CHECK(x, err) \
if (!(x)) { \
fprintf(stderr, "ERROR: %s\n", err); \
return EXIT_FAILURE; \
}
#define LEN_OF(x) \
((sizeof (x)) / (sizeof (x)[0]))
static void lognumber(wasm_exec_env_t exec, int32_t n) {
printf("-- %d\n", n);
}
int main(int argc, char *argv[argc + 1]) {
uint8_t wasm[1024];
size_t wasmsz;
{
FILE *f = fopen("fibonacci.wasm", "r");
P_CHECK(f, "fopen");
wasmsz = fread(wasm, 1, sizeof wasm, f);
P_CHECK(wasmsz, "fread");
P_CHECK(fclose(f) == 0, "fclose");
}
bool ok;
char err[1024];
uint8_t heap[16 * 1024 * 1024];
struct RuntimeInitArgs init = {
.mem_alloc_type = Alloc_With_Pool,
.mem_alloc_option.pool.heap_buf = heap,
.mem_alloc_option.pool.heap_size = sizeof heap,
.native_module_name = "fibonacci.wasm",
.native_symbols = NULL,
.n_native_symbols = 0,
.running_mode = Mode_Interp,
};
wasm_runtime_full_init(&init);
struct NativeSymbol env[] = {
{"lognumber", lognumber, "(i)"},
};
WAMR_CHECK(wasm_runtime_register_natives("env", env, LEN_OF(env)),
"failed to register natives");
wasm_module_t module = wasm_runtime_load(wasm, wasmsz, err, sizeof err);
WAMR_CHECK(module, err);
wasm_module_inst_t instance = wasm_runtime_instantiate(module, 8092, 0, err, sizeof err);
WAMR_CHECK(instance, err);
wasm_function_inst_t function = wasm_runtime_lookup_function(instance, "fibonacci");
WAMR_CHECK(function, "could not find function");
wasm_exec_env_t exec = wasm_runtime_create_exec_env(instance, 1024);
WAMR_CHECK(exec, "failed to create execution environment");
int32_t result;
{
uint32_t args[] = {10};
WAMR_CHECK(wasm_runtime_call_wasm(exec, function, LEN_OF(args), args),
"failed to call 'fibonacci' function");
result = args[0];
}
printf("=> %d\n", result);
return EXIT_SUCCESS;
}
|