|
| 1 | +# coding: utf-8 |
| 2 | +$LOAD_PATH.unshift File.expand_path("../../lib", __FILE__) |
| 3 | + |
| 4 | +require "wasmer" |
| 5 | + |
| 6 | +# Instantiates the module. |
| 7 | +file = File.expand_path "greet.wasm", File.dirname(__FILE__) |
| 8 | +bytes = IO.read file, mode: "rb" |
| 9 | +instance = Wasmer::Instance.new bytes |
| 10 | + |
| 11 | +# Set the subject to greet. |
| 12 | +subject = "Wasmer π".bytes |
| 13 | +length_of_subject = subject.length |
| 14 | + |
| 15 | +# Allocate memory for the subject, and get a pointer to it. |
| 16 | +input_pointer = instance.exports.allocate length_of_subject |
| 17 | + |
| 18 | +# Write the subject into the memory. |
| 19 | +memory = instance.memory.uint8_view input_pointer |
| 20 | + |
| 21 | +for nth in 0..length_of_subject - 1 |
| 22 | + memory[nth] = subject[nth] |
| 23 | +end |
| 24 | + |
| 25 | +# C-string terminates by NULL. |
| 26 | +memory[length_of_subject] = 0 |
| 27 | + |
| 28 | +# Run the `greet` function. Give the pointer to the subject. |
| 29 | +output_pointer = instance.exports.greet input_pointer |
| 30 | + |
| 31 | +# Read the result of the `greet` function. |
| 32 | +memory = instance.memory.uint8_view output_pointer |
| 33 | + |
| 34 | +output = "" |
| 35 | +nth = 0 |
| 36 | + |
| 37 | +while true |
| 38 | + char = memory[nth] |
| 39 | + |
| 40 | + if 0 == char |
| 41 | + break |
| 42 | + end |
| 43 | + |
| 44 | + output += char.chr |
| 45 | + nth += 1 |
| 46 | +end |
| 47 | + |
| 48 | +length_of_output = nth |
| 49 | + |
| 50 | +puts output |
| 51 | + |
| 52 | +# Deallocate the subject, and the output. |
| 53 | +instance.exports.deallocate(input_pointer, length_of_subject) |
| 54 | +instance.exports.deallocate(output_pointer, length_of_output) |
0 commit comments