WebAssembly - Làm việc với Rust
Để có được mã biên dịch RUST, chúng tôi sẽ sử dụng công cụ WebAssembly.studio.
Đến WebAssembly.studio trong đó có sẵn tại Đếnhttps://webassembly.studio/ và nó sẽ hiển thị cho bạn màn hình như hình dưới đây -
![](https://post.nghiatu.com/assets/tutorial/webassembly/images/rust_compile_code.jpg)
Nhấn vào Empty Rust Project. Sau khi hoàn tất, bạn sẽ nhận được ba tệp trong thư mục src / -
![](https://post.nghiatu.com/assets/tutorial/webassembly/images/get_three_files.jpg)
Mở tệp main.rs và thay đổi mã bạn chọn.
Tôi đang thêm hàm sau sẽ thêm hai số nhất định:
fn add_ints(lhs: i32, rhs: i32) -> i32 {
lhs+rhs
}
Mã có sẵn trong main.rs như sau:
#[no_mangle]
pub extern "C" fn add_one(x: i32) -> i32 {
x + 1
}
Thay thế add_one fn bằng của bạn như hình dưới đây -
#[no_mangle]
pub extern "C" fn add_ints(lhs: i32, rhs: i32) -> i32 {
lhs+rhs
}
Trong main.js, thay đổi tên hàm từ add_one thành add_ints
fetch('../out/main.wasm').then(
response =>
response.arrayBuffer()
).then(bytes => WebAssembly.instantiate(bytes)).then(results => {
instance = results.instance;
document.getElementById("container").textContent = instance.exports.add_one(41);
}).catch(console.error);
Thay thế instance.exports.add_one thành instance.exports.add_ints (100,100)
fetch('../out/main.wasm').then(
response =>
response.arrayBuffer()
).then(bytes => WebAssembly.instantiate(bytes)).then(results => {
instance = results.instance;
document.getElementById("container").textContent = instance.exports.add_ints(100,100)
}).catch(console.error);
Nhấp vào nút xây dựng có sẵn trên giao diện người dùng webassembly.studio để xây dựng mã.
![](https://post.nghiatu.com/assets/tutorial/webassembly/images/webassembly_studio_ui.jpg)
Sau khi xây dựng xong, hãy nhấp vào nút Chạy có sẵn trên giao diện người dùng, để xem kết quả -
![](https://post.nghiatu.com/assets/tutorial/webassembly/images/run_button.jpg)
Chúng tôi nhận được kết quả đầu ra là 200, khi chúng tôi truyền instance.exports.add_ints (100,100).
Tương tự như vậy, bạn có thể viết một chương trình khác cho gỉ và biên dịch nó trong webassembly.studio.