Skip to content

Commit a0f1ffb

Browse files
Add WASI hello world program example
1 parent 663fcfa commit a0f1ffb

File tree

2 files changed

+27
-0
lines changed

2 files changed

+27
-0
lines changed

Examples/hello.swift

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
// Compile: swiftc ./hello.swift -o hello.wasm -target wasm32-unknown-none-wasm -enable-experimental-feature Extern -enable-experimental-feature Embedded -wmo -Xcc -fdeclspec -Xclang-linker -nostdlib -Xfrontend -disable-stack-protector -Osize
2+
// Swift version: DEVELOPMENT-SNAPSHOT-2024-06-13-a
3+
4+
// This is a simple WASI program written in Embedded Swift.
5+
6+
@_extern(wasm, module: "wasi_snapshot_preview1", name: "fd_write")
7+
@_extern(c)
8+
func fd_write(fd: Int32, iovs: UnsafeRawPointer, iovs_len: Int32, nwritten: UnsafeMutablePointer<Int32>) -> Int32
9+
10+
func _print(_ string: StaticString) {
11+
string.withUTF8Buffer { string in
12+
withUnsafeTemporaryAllocation(byteCount: 8, alignment: 4) { iov in
13+
let iov = iov.baseAddress!
14+
iov.advanced(by: 0).storeBytes(of: string.baseAddress!, as: UnsafeRawPointer.self)
15+
iov.advanced(by: 4).storeBytes(of: Int32(string.count), as: Int32.self)
16+
var nwritten: Int32 = 0
17+
_ = fd_write(fd: 1, iovs: iov, iovs_len: 1, nwritten: &nwritten)
18+
}
19+
}
20+
}
21+
22+
// The entry point of this WASI program.
23+
@_expose(wasm, "_start")
24+
@_cdecl("_start")
25+
func _start() {
26+
_print("Hello, World!\n")
27+
}

Examples/hello.wasm

286 Bytes
Binary file not shown.

0 commit comments

Comments
 (0)