1#include <stdio.h> 2#include <stdlib.h> 3#include <string.h> 4#include <inttypes.h> 5 6#include "wasm.h" 7 8#define own 9 10// A function to be called from Wasm code. 11own wasm_trap_t* hello_callback( 12 const wasm_val_t args[], wasm_val_t results[] 13) { 14 printf("Calling back...\n"); 15 printf("> Hello World!\n"); 16 return NULL; 17} 18 19 20int main(int argc, const char* argv[]) { 21 // Initialize. 22 printf("Initializing...\n"); 23 wasm_engine_t* engine = wasm_engine_new(); 24 wasm_store_t* store = wasm_store_new(engine); 25 26 // Load binary. 27 printf("Loading binary...\n"); 28 FILE* file = fopen("hello.wasm", "r"); 29 if (!file) { 30 printf("> Error loading module!\n"); 31 return 1; 32 } 33 fseek(file, 0L, SEEK_END); 34 size_t file_size = ftell(file); 35 fseek(file, 0L, SEEK_SET); 36 wasm_byte_vec_t binary; 37 wasm_byte_vec_new_uninitialized(&binary, file_size); 38 if (fread(binary.data, file_size, 1, file) != 1) { 39 printf("> Error loading module!\n"); 40 return 1; 41 } 42 fclose(file); 43 44 // Compile. 45 printf("Compiling module...\n"); 46 own wasm_module_t* module = wasm_module_new(store, &binary); 47 if (!module) { 48 printf("> Error compiling module!\n"); 49 return 1; 50 } 51 52 wasm_byte_vec_delete(&binary); 53 54 // Create external print functions. 55 printf("Creating callback...\n"); 56 own wasm_functype_t* hello_type = wasm_functype_new_0_0(); 57 own wasm_func_t* hello_func = 58 wasm_func_new(store, hello_type, hello_callback); 59 60 wasm_functype_delete(hello_type); 61 62 // Instantiate. 63 printf("Instantiating module...\n"); 64 const wasm_extern_t* imports[] = { wasm_func_as_extern(hello_func) }; 65 own wasm_instance_t* instance = 66 wasm_instance_new(store, module, imports, NULL); 67 if (!instance) { 68 printf("> Error instantiating module!\n"); 69 return 1; 70 } 71 72 wasm_func_delete(hello_func); 73 74 // Extract export. 75 printf("Extracting export...\n"); 76 own wasm_extern_vec_t exports; 77 wasm_instance_exports(instance, &exports); 78 if (exports.size == 0) { 79 printf("> Error accessing exports!\n"); 80 return 1; 81 } 82 const wasm_func_t* run_func = wasm_extern_as_func(exports.data[0]); 83 if (run_func == NULL) { 84 printf("> Error accessing export!\n"); 85 return 1; 86 } 87 88 wasm_module_delete(module); 89 wasm_instance_delete(instance); 90 91 // Call. 92 printf("Calling export...\n"); 93 if (wasm_func_call(run_func, NULL, NULL)) { 94 printf("> Error calling function!\n"); 95 return 1; 96 } 97 98 wasm_extern_vec_delete(&exports); 99 100 // Shut down. 101 printf("Shutting down...\n"); 102 wasm_store_delete(store); 103 wasm_engine_delete(engine); 104 105 // All done. 106 printf("Done.\n"); 107 return 0; 108} 109