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
strlencounts 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()givesnonefor a null pointer, asgetenvreturns for a variable that isn't set.- If the library says its text must be freed, freeing it is up to your program.