ffi

MoonBit Foreign Function Interface.

ffi
bindings
abi
utils
moon add moonbit-community/ffi@0.1.14
Download zip
Version
0.1.14
License
Apache-2.0
Last updated
10 days ago
Downloads
26

Dependencies

README

#moonbit-community/ffi

Helpers for converting MoonBit String values to and from null-terminated UTF-8 and UTF-16LE buffers at FFI boundaries.

Originally developed at justjavac/moonbit-ffi; now maintained inside the Proton repository and licensed under Apache-2.0.

#Usage

///|
test {
let c_name = @ffi.to_cstr("ffi")
assert_eq(c_name, b"ffi\x00")
assert_eq(@ffi.from_cstr(c_name), "ffi")

let wide_name = @ffi.to_wstr("世界")
assert_eq(@ffi.from_wstr_lossy(wide_name), "世界")
}

#
from_cstr

fn from_cstr(b : Bytes) -> String

Decode a null-terminated UTF-8 buffer into a MoonBit String.

from_cstr requires a trailing \x00, removes that terminator, and then decodes the remaining bytes as UTF-8. Invalid byte sequences are replaced with the Unicode replacement character so callers can safely inspect or log malformed input that came from native code.

Parameters

  • b: A C-style byte buffer that must end with \x00

Returns

The decoded string without the trailing null byte.

Panics

Aborts if b is empty or does not end with \x00.

Example

let raw = @ffi.to_cstr("hello")
inspect(@ffi.from_cstr(raw), content="hello")

#
from_wstr_lossy

fn from_wstr_lossy(b : Bytes) -> String

Decode a null-terminated UTF-16LE buffer into a MoonBit String.

The trailing wide null (\x00\x00) is required and removed before decoding. Invalid UTF-16 sequences are replaced with the Unicode replacement character, which keeps the function safe for lossy logging and interop code.

Parameters

  • b: A UTF-16LE byte buffer that must end with \x00\x00

Returns

The decoded string without the trailing wide null.

Panics

Aborts if b is shorter than two bytes or is missing the trailing wide null terminator.

Example

let raw = @ffi.to_wstr("Hello")
inspect(@ffi.from_wstr_lossy(raw), content="Hello")

#
to_cstr

fn to_cstr(s : String) -> Bytes

Encode a MoonBit String as a null-terminated UTF-8 buffer.

This is the companion to from_cstr. The returned Bytes value is suitable for passing to C APIs that expect UTF-8 char* input terminated by a single zero byte.

Parameters

  • s: The MoonBit string to encode

Returns

UTF-8 bytes for s followed by a trailing \x00.

Example

inspect(@ffi.to_cstr("ffi"), content=b"ffi\x00")

#
to_wstr

fn to_wstr(s : String) -> Bytes

Encode a MoonBit String as a null-terminated UTF-16LE buffer.

Use this when calling Windows APIs that accept wchar_t* or LPCWSTR values. The returned bytes always end with a wide null terminator.

Parameters

  • s: The MoonBit string to encode

Returns

UTF-16LE bytes for s followed by \x00\x00.

Example

inspect(@ffi.to_wstr("Hi"), content=b"\x48\x00\x69\x00\x00\x00")

Source Files