| 56 | |
| 57 | |
| 58 | void run() { |
| 59 | // Initialize. |
| 60 | std::cout << "Initializing..." << std::endl; |
| 61 | auto engine = wasm::Engine::make(); |
| 62 | auto store_ = wasm::Store::make(engine.get()); |
| 63 | auto store = store_.get(); |
| 64 | |
| 65 | // Load binary. |
| 66 | std::cout << "Loading binary..." << std::endl; |
| 67 | std::ifstream file("callback.wasm"); |
| 68 | file.seekg(0, std::ios_base::end); |
| 69 | auto file_size = file.tellg(); |
| 70 | file.seekg(0); |
| 71 | auto binary = wasm::vec<byte_t>::make_uninitialized(file_size); |
| 72 | file.read(binary.get(), file_size); |
| 73 | file.close(); |
| 74 | if (file.fail()) { |
| 75 | std::cout << "> Error loading module!" << std::endl; |
| 76 | exit(1); |
| 77 | } |
| 78 | |
| 79 | // Compile. |
| 80 | std::cout << "Compiling module..." << std::endl; |
| 81 | auto module = wasm::Module::make(store, binary); |
| 82 | if (!module) { |
| 83 | std::cout << "> Error compiling module!" << std::endl; |
| 84 | exit(1); |
| 85 | } |
| 86 | |
| 87 | // Create external print functions. |
| 88 | std::cout << "Creating callback..." << std::endl; |
| 89 | auto print_type = wasm::FuncType::make( |
| 90 | wasm::ownvec<wasm::ValType>::make(wasm::ValType::make(wasm::ValKind::I32)), |
| 91 | wasm::ownvec<wasm::ValType>::make(wasm::ValType::make(wasm::ValKind::I32)) |
| 92 | ); |
| 93 | auto print_func = wasm::Func::make(store, print_type.get(), print_callback); |
| 94 | |
| 95 | // Creating closure. |
| 96 | std::cout << "Creating closure..." << std::endl; |
| 97 | int i = 42; |
| 98 | auto closure_type = wasm::FuncType::make( |
| 99 | wasm::ownvec<wasm::ValType>::make(), |
| 100 | wasm::ownvec<wasm::ValType>::make(wasm::ValType::make(wasm::ValKind::I32)) |
| 101 | ); |
| 102 | auto closure_func = wasm::Func::make(store, closure_type.get(), closure_callback, &i); |
| 103 | |
| 104 | // Instantiate. |
| 105 | std::cout << "Instantiating module..." << std::endl; |
| 106 | auto imports = wasm::vec<wasm::Extern*>::make( |
| 107 | print_func.get(), closure_func.get()); |
| 108 | auto instance = wasm::Instance::make(store, module.get(), imports); |
| 109 | if (!instance) { |
| 110 | std::cout << "> Error instantiating module!" << std::endl; |
| 111 | exit(1); |
| 112 | } |
| 113 | |
| 114 | // Extract export. |
| 115 | std::cout << "Extracting export..." << std::endl; |