Skip to main content

Foreign functions

0.1.1

Embedding C, C++ and Rust function bodies directly in Sarlin source.

Declaring a foreign function

foreign.sar
external Rust func add(left int32, right int32) int32
    left + right
end external

func main() {
    print(add(20, 22))
}

Sarlin owns the declaration and the selected language supplies the body. Write external, then C, Cpp or Rust, then an ordinary func declaration. The body begins on the next line and runs until end external appears on a line of its own. Any other language name reports expected C, Cpp, or Rust.

Call a foreign function exactly like a Sarlin function. One project may mix C, C++ and Rust functions freely.

mixed.sar
external C func scale(value int32) int32
    return value * 2;
end external

external Cpp func combine(left float64, right float64) float64
    return left + right;
end external

external Rust func offset(value int64) int64
    value + 7
end external

func main() {
    print(scale(21))
    print(combine(1.5, 2.5))
    print(offset(35))
}

Types at the boundary

Parameters and return values may be int32, int64, uint32, uint64, float32 or float64. Omit the return type for a function that returns nothing.

void.sar
external C func observe(value uint64)
    (void)value;
end external

func main() {
    observe(42)
}

Toolchains

Building a C function requires Clang, a C++ function requires clang++, and a Rust function requires rustc. Sarlin reports a missing toolchain, and reports errors from the native compiler with the language and the foreign function that produced them. Generated native source and library files are removed after the build, whether it succeeded or failed.

A foreign function name may not begin with sarlin_. That prefix is reserved for the Sarlin runtime and is rejected during checking.