Skip to content
Kavachकवच

Calling C: Text

● Advanced3 min

A String goes to C as a copy ending in a zero byte. Text C gives back comes as a Ptr<UInt8>, and .text() copies it.

extern c "c" {
    fn strlen(s: String) -> UInt64
    fn getenv(name: String) -> Ptr<UInt8>
}

fn c_length(s: String) -> UInt64 {
    unsafe { strlen(s) }
}

fn env_var(name: String) -> String? {
    unsafe { getenv(name).text() }
}

fn main() {
    print(c_length("namaste"))
    print(c_length("नमस्ते"))
    print(env_var("PATH") != none)
    print(env_var("KAVACH_DOCS_NOT_SET") ?? "not set")
}

The program ran and printed:

kavach run

718truenot set
src/main.kav: Kavach code, then what running it prints
  • strlen counts bytes, as C does: नमस्ते is 6 characters but 18 bytes in UTF-8.
  • The copy C gets is valid only during the call: C must not keep it.
  • .text() gives none for a null pointer, as getenv returns for a variable that isn't set.
  • If the library says its text must be freed, freeing it is up to your program.