Skip to content

Commit d32ee2c

Browse files
bors[bot]Hywan
andcommitted
Merge #12
12: doc(examples) Add the `greet` example. r=Hywan a=Hywan ```sh $ ruby examples/greet.rb $ Hello, Wasmer πŸ’Ž! ``` πŸ˜„ Co-authored-by: Ivan Enderlin <[email protected]>
2 parents 7b6024b + 49642ef commit d32ee2c

File tree

3 files changed

+83
-0
lines changed

3 files changed

+83
-0
lines changed

β€Žexamples/greet.rb

+54
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
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)

β€Žexamples/greet.rs

+29
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
use std::ffi::{CStr, CString};
2+
use std::mem;
3+
use std::os::raw::{c_char, c_void};
4+
5+
#[no_mangle]
6+
pub extern fn allocate(size: usize) -> *mut c_void {
7+
let mut buffer = Vec::with_capacity(size);
8+
let pointer = buffer.as_mut_ptr();
9+
mem::forget(buffer);
10+
11+
pointer as *mut c_void
12+
}
13+
14+
#[no_mangle]
15+
pub extern fn deallocate(pointer: *mut c_void, capacity: usize) {
16+
unsafe {
17+
let _ = Vec::from_raw_parts(pointer, 0, capacity);
18+
}
19+
}
20+
21+
#[no_mangle]
22+
pub extern fn greet(subject: *mut c_char) -> *mut c_char {
23+
let subject = unsafe { CStr::from_ptr(subject).to_bytes().to_vec() };
24+
let mut output = b"Hello, ".to_vec();
25+
output.extend(&subject);
26+
output.extend(&[b'!']);
27+
28+
unsafe { CString::from_vec_unchecked(output) }.into_raw()
29+
}

β€Žexamples/greet.wasm

13.1 KB
Binary file not shown.

0 commit comments

Comments
Β (0)