728x90
WebAssambly (wasm)
웹 브라우저에서 실되는 프로그래밍 언어이자 바이트코드.
• 안전하다
• 빠르다
WebAssembly System Interface (WASI)
WebAssembly용 모듈식 시스템 인터페이스
- Cross platform applications and games
- Code re-use between platforms and use cases
- Running applications written in any Wasm/Wasi-compilable language on single runtime
- "Containerizing" application and their dependencies as single taget
- And Many More!
브라우저 외부에서 WebAssembly를 실행할 수 있다
WASI는 Filesystem, Networking, Time, Random 등과 같은 시스템 리소스에 액세스하기 위한 WebAssembly 모듈용 표준화된 API를 제공한다.
Host
WebAssembly 모듈을 실행하는 WebAssembly 런타임
- wasmedge : https://wasmedge.org/
- wasmtime : https://wasmtime.dev/
WebAssambly
rust의 wasm-pack을 사용하여 wasm을 생성하고 html을 사용하여 테스트한다.
cargo.toml
[package]
name = "hello"
version = "0.1.0"
edition = "2021"
[lib]
crate-type - ["cdylib"]
[dependencies]
wasm-bindgen = "0.2.84"
lib.rs
use wasm_bindgen::prelude::*;
#[wasm_bindgen]
pub fn add(a: i32, b: i32) -> i32 {
a + b
}
build
wasm-pack build --target web
javascript
// Import our outputted wasm ES6 module
// Which, export default's, an initialization function
import init from "./pkg/hello.js"
const runWasm = async() => {
// Instantiate our wasm module
const hello = await init(". /pkg/hello_bg.wasm");
// Call the Add function export from wasm, save the result
const addResult = hello. add (24, 28);
// Set the result onto the body
document. body. textContent = 'Hello World! addResult: ${addResult)';
};
runWasm();
index.html
<!DOCTYPE html>
<htm1>
<head>
<meta charset-"UTF-8" />
<title›Hello World - Rust</title›
<script type="module" src="./index.js"›</script>
</head>
<body></body>
</html>
Result
Hello World! addResult: 52
Standlon WebAssembly
main.rs
fn main() {
printIn!("Hello, world!");
}
run
$ cargo build --target wasm32-wasi
$ wasmtime target/wasm32-wasi/debug/hello-world.wasm
=> Hello, world!
Rust에서 컴파일된 WebAssembly 함수 호출
main.rs
#[no mangle]
pub fn add(left: usize, right: usize) -> usize {
left + right
}
run
cargo build --target wasm32-wasi
wasmedge --reactor lib_test.wasm add 2 2
=› 4
참고
'dev > rust' 카테고리의 다른 글
Rust - Understading Ownership (0) | 2024.06.02 |
---|