IMPORTANT: To view this page as Markdown, append `.md` to the URL (e.g. /docs/manual/basics.md). For the complete Mojo documentation index, see llms.txt.
Skip to main content
Version: 1.0.0
For the complete Mojo documentation index, see llms.txt. Markdown versions of all pages are available by appending .md to any URL (e.g. /docs/manual/basics.md).

external_call

def external_call[callee: StringSpan[ImmStaticOrigin], return_type: RegisterPassable, *types: AnyType, *, num_fixed_args: OptionalReg[Int] = None](*args: *types.values) -> return_type

Calls an external function.

By default every argument is a fixed argument of a non-variadic callee. Pass num_fixed_args to call a C variadic function such as open() or snprintf(), giving how many of the first arguments are fixed arguments of the callee; the arguments after those are passed as variadic arguments. This matters because ABIs such as AAPCS on ARM64 macOS pass variadic arguments differently from fixed ones.

Examples:

from std.ffi import c_char, c_int, external_call

# int open(const char *path, int oflag, ...);
var path_str = path
var fd = external_call["open", c_int, num_fixed_args=2](
path_str.as_c_string_slice().unsafe_ptr(), c_int(flags), c_int(0o666)
)

Constraints:

num_fixed_args must not be negative.

Parameters:

  • callee (StringSpan[ImmStaticOrigin]): The name of the external function.
  • return_type (RegisterPassable): The return type.
  • *types (AnyType): The argument types.
  • num_fixed_args (OptionalReg[Int]): The number of fixed arguments of a C variadic callee, or None for a non-variadic callee. A count of 0 declares a callee whose every argument is variadic, which None cannot express. An argument pack is flattened into one argument per element, so the count must cover the elements rather than the pack, and the fixed arguments must precede any pack.

Args:

  • *args (*types.values): The arguments to pass to the external function.

Returns:

return_type: The external call result.