lotsoftools

Understanding Rust Error E0060

Rust Error E0060: Variadic Functions Arity

Rust Error E0060 occurs when calling an external variadic C function with an incorrect number of arguments. In Rust, external C functions can be variadic, meaning they can accept a varying number of arguments. However, even variadic functions have a minimum number of arguments they must receive.

Consider C's variadic printf function:

use std::os::raw::{c_char, c_int};

extern "C" {
    fn printf(_: *const c_char, ...) -> c_int;
}

unsafe { printf(); } // error!

With this declaration, the printf function requires at least one argument. Invoking printf() without any arguments is invalid and triggers Rust Error E0060.

Correct Usage of Variadic Functions

To correctly use a variadic function like printf in Rust, you must provide a minimum number of arguments. Here's an example demonstrating valid usage of the printf function:

use std::os::raw::{c_char, c_int};
#[cfg_attr(all(windows, target_env = "msvc"),
           link(name = "legacy_stdio_definitions",
                kind = "static", modifiers = "-bundle"))]
extern "C" { fn printf(_: *const c_char, ...) -> c_int; }
fn main() {
unsafe {
    use std::ffi::CString;

    let fmt = CString::new("test\n").unwrap();
    printf(fmt.as_ptr());

    let fmt = CString::new("number = %d\n").unwrap();
    printf(fmt.as_ptr(), 3);

    let fmt = CString::new("%d, %d\n").unwrap();
    printf(fmt.as_ptr(), 10, 5);
}
}

In the example above, we use the CString type to create a C-compatible string and pass the correct number of arguments to the printf function, avoiding Rust Error E0060.

Conclusion

Rust Error E0060 is encountered when invoking an external variadic C function with an incorrect number of arguments. To resolve this error, ensure that the minimum number of arguments are provided when calling a variadic function. Understanding how to work with variadic functions and utilizing Rust's CString type for proper string manipulation, you can effectively interface with external C functions without encountering E0060.

Recommended Reading