Sign in

    This version of the module is deprecated: This package is deprecated. moonbit-community/ffi should be preferred.

    ffi

    MoonBit Foreign Function Interface.

    ffi
    bindings
    abi
    utils
    Download zip
    Author
    Version
    0.1.8
    License
    MIT
    Last updated
    last year
    Downloads
    25K

    #MoonBit FFI

    A lightweight utility library for converting between C‐style null-terminated byte strings (Bytes) and MoonBit String values.

    Build Status

    #Features

    • from_cstr: Convert a null-terminated Bytes to a MoonBit String (drops the \x00 terminator).
    • to_cstr: Convert a MoonBit String to null-terminated Bytes.

    #Installation

    Add justjavac/ffi to your dependencies:

    moon update moon add justjavac/ffi

    #Usage

    // Convert Bytes → String
    let data = b"Hello, world!\x00"
    let s = @ffi.from_cstr(data)
    assert_eq!(s, "Hello, world!")

    // Convert String → Bytes
    let cstr = @ffi.to_cstr("Hello, world!")
    assert_eq!(cstr, data)

    #Supported Backends

    • Wasm & WasmGC
    • JavaScript
    • Native
    • LLVM

    #Development

    Build the library and run tests (including docs):

    moon build moon test --doc

    #License

    This project is licensed under the MIT License. © justjavac

    from_cstr

    fn from_cstr(b : Bytes) -> String
    ! Converts a byte array to a String and vice versa, handling null-termination.

    Parameters:
    • b: A byte array that is expected to be null-terminated.

    Returns:
    • A String representation of the byte array, excluding the null terminator.

    Example:
    let s = from_cstr(b"Hello, world!\x00")
    assert_eq(s, "Hello, world!")

    from_wstr_lossy

    fn from_wstr_lossy(b : Bytes) -> String
    ! Converts a byte array to a String and vice versa, handling null-termination.

    Parameters:
    • b: A byte array that is expected to be null-terminated.

    Returns:
    • A String representation of the byte array, excluding the null terminator.

    Example:
    let s = from_wstr_lossy(b"\x48\x00\x65\x00\x6c\x00\x6c\x00\x6f\x00\x00\x00")
    assert_eq(s, "Hello")

    to_cstr

    fn to_cstr(s : String) -> Bytes
    Converts a String to a C-style null-terminated byte array.

    Parameters:
    • s: A String that will be converted to a null-terminated byte array.

    Returns:
    • A Bytes object containing the null-terminated byte representation of the string.

    Example:
    let cstr = to_cstr("Hello, world!")
    assert_eq(cstr, b"Hello, world!\x00")

    to_wstr

    fn to_wstr(s : String) -> Bytes
    Converts a String to a C-style null-terminated byte array.

    Parameters:
    • s: A String that will be converted to a null-terminated byte array.

    Returns:
    • A Bytes object containing the null-terminated byte representation of the string.

    Example:
    let wstr = to_wstr("Hello")
    assert_eq(wstr, b"\x48\x00\x65\x00\x6c\x00\x6c\x00\x6f\x00\x00\x00")

    Source Files