| 21 | |
| 22 | |
| 23 | void run( |
| 24 | wasm::Engine* engine, const wasm::Shared<wasm::Module>* shared, |
| 25 | std::mutex* mutex, int id |
| 26 | ) { |
| 27 | // Create store. |
| 28 | auto store_ = wasm::Store::make(engine); |
| 29 | auto store = store_.get(); |
| 30 | |
| 31 | // Obtain. |
| 32 | auto module = wasm::Module::obtain(store, shared); |
| 33 | if (!module) { |
| 34 | std::lock_guard<std::mutex> lock(*mutex); |
| 35 | std::cout << "> Error compiling module!" << std::endl; |
| 36 | exit(1); |
| 37 | } |
| 38 | |
| 39 | // Run the example N times. |
| 40 | for (int i = 0; i < N_REPS; ++i) { |
| 41 | std::this_thread::sleep_for(std::chrono::nanoseconds(100000)); |
| 42 | |
| 43 | // Create imports. |
| 44 | auto func_type = wasm::FuncType::make( |
| 45 | wasm::ownvec<wasm::ValType>::make(wasm::ValType::make(wasm::ValKind::I32)), |
| 46 | wasm::ownvec<wasm::ValType>::make() |
| 47 | ); |
| 48 | auto func = wasm::Func::make(store, func_type.get(), callback, mutex); |
| 49 | |
| 50 | auto global_type = wasm::GlobalType::make( |
| 51 | wasm::ValType::make(wasm::ValKind::I32), wasm::Mutability::CONST); |
| 52 | auto global = wasm::Global::make( |
| 53 | store, global_type.get(), wasm::Val::i32(i)); |
| 54 | |
| 55 | // Instantiate. |
| 56 | auto imports = wasm::vec<wasm::Extern*>::make(func.get(), global.get()); |
| 57 | auto instance = wasm::Instance::make(store, module.get(), imports); |
| 58 | if (!instance) { |
| 59 | std::lock_guard<std::mutex> lock(*mutex); |
| 60 | std::cout << "> Error instantiating module!" << std::endl; |
| 61 | exit(1); |
| 62 | } |
| 63 | |
| 64 | // Extract export. |
| 65 | auto exports = instance->exports(); |
| 66 | if (exports.size() == 0 || exports[0]->kind() != wasm::ExternKind::FUNC || !exports[0]->func()) { |
| 67 | std::lock_guard<std::mutex> lock(*mutex); |
| 68 | std::cout << "> Error accessing export!" << std::endl; |
| 69 | exit(1); |
| 70 | } |
| 71 | auto run_func = exports[0]->func(); |
| 72 | |
| 73 | // Call. |
| 74 | auto empty = wasm::vec<wasm::Val>::make(); |
| 75 | run_func->call(empty, empty); |
| 76 | } |
| 77 | } |
| 78 | |
| 79 | int main(int argc, const char *argv[]) { |
| 80 | // Initialize. |