WrongMethodTypeException in invokeExact()

Cause: Java’s MethodHandle.invokeExact() requires an exact match between arguments and the function signature. A mismatch in argument types or order will throw this error.

Solution:

  1. Verify FunctionDescriptor: Ensure that the FunctionDescriptor matches the Rust function’s expected argument and return types exactly.
  2. Check Argument Casts: Explicitly cast arguments to their expected types, and cast return values as needed.

Example:

#![allow(unused)]
fn main() {
// Rust function signature: pub extern "C" fn add(x: i32, y: i32) -> i32
FunctionDescriptor addDescriptor = FunctionDescriptor.of(ValueLayout.JAVA_INT, ValueLayout.JAVA_INT, ValueLayout.JAVA_INT);
MethodHandle addHandle = linker.downcallHandle(lib.find("add").orElseThrow(), addDescriptor);

int result = (int) addHandle.invokeExact(5, 3);  // Cast to int as expected
}

Explanation and Solution:

Type Matching: FunctionDescriptor ensures that Java and Rust types align.

Exact Casting: Casting return values and arguments to their exact types avoids this error, as Java’s type system is stricter here than Rust’s.

Why It’s Tricky:

Rust function signatures may allow implicit casting that Java does not, so ensuring exact types in the descriptor is essential.