MCPcopy Create free account
hub / github.com/WebAssembly/wasm-c-api / main

Function main

example/callback.c:63–167  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

61
62
63int main(int argc, const char* argv[]) {
64 // Initialize.
65 printf("Initializing...\n");
66 wasm_engine_t* engine = wasm_engine_new();
67 wasm_store_t* store = wasm_store_new(engine);
68
69 // Load binary.
70 printf("Loading binary...\n");
71 FILE* file = fopen("callback.wasm", "rb");
72 if (!file) {
73 printf("> Error loading module!\n");
74 return 1;
75 }
76 fseek(file, 0L, SEEK_END);
77 size_t file_size = ftell(file);
78 fseek(file, 0L, SEEK_SET);
79 wasm_byte_vec_t binary;
80 wasm_byte_vec_new_uninitialized(&binary, file_size);
81 if (fread(binary.data, file_size, 1, file) != 1) {
82 printf("> Error loading module!\n");
83 return 1;
84 }
85 fclose(file);
86
87 // Compile.
88 printf("Compiling module...\n");
89 own wasm_module_t* module = wasm_module_new(store, &binary);
90 if (!module) {
91 printf("> Error compiling module!\n");
92 return 1;
93 }
94
95 wasm_byte_vec_delete(&binary);
96
97 // Create external print functions.
98 printf("Creating callback...\n");
99 own wasm_functype_t* print_type = wasm_functype_new_1_1(wasm_valtype_new_i32(), wasm_valtype_new_i32());
100 own wasm_func_t* print_func = wasm_func_new(store, print_type, print_callback);
101
102 int i = 42;
103 own wasm_functype_t* closure_type = wasm_functype_new_0_1(wasm_valtype_new_i32());
104 own wasm_func_t* closure_func = wasm_func_new_with_env(store, closure_type, closure_callback, &i, NULL);
105
106 wasm_functype_delete(print_type);
107 wasm_functype_delete(closure_type);
108
109 // Instantiate.
110 printf("Instantiating module...\n");
111 wasm_extern_t* externs[] = {
112 wasm_func_as_extern(print_func), wasm_func_as_extern(closure_func)
113 };
114 wasm_extern_vec_t imports = WASM_ARRAY_VEC(externs);
115 own wasm_instance_t* instance =
116 wasm_instance_new(store, module, &imports, NULL);
117 if (!instance) {
118 printf("> Error instantiating module!\n");
119 return 1;
120 }

Callers

nothing calls this directly

Calls 10

wasm_engine_newFunction · 0.85
wasm_store_newFunction · 0.85
wasm_module_newFunction · 0.85
wasm_func_newFunction · 0.85
wasm_func_new_with_envFunction · 0.85
wasm_func_as_externFunction · 0.85
wasm_instance_newFunction · 0.85
wasm_instance_exportsFunction · 0.85
wasm_extern_as_funcFunction · 0.85
wasm_func_callFunction · 0.85

Tested by

no test coverage detected