0Pricing
Java Academy · Lesson

Downcall Handles

Call native functions.

Downcall Handles is a free Java Academy lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Java Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Calling Native Functions

A downcall is a call from Java down into native code. FFM represents each native function as a MethodHandle built from a Linker.

This lesson walks through finding, describing, and invoking a C function.

The Native Linker

Linker.nativeLinker() returns the linker for the running platform. It knows the C calling convention and can produce handles to native functions.

import java.lang.foreign.Linker;

public class Main {
    public static void main(String[] args) {
        Linker linker = Linker.nativeLinker();
        System.out.println("Got native linker: " + linker);
    }
}

Finding a Symbol

You need the function's address. linker.defaultLookup() searches the standard C library; SymbolLookup.libraryLookup(name, arena) loads a specific shared library.

import java.lang.foreign.*;

public class Main {
    public static void main(String[] args) {
        Linker linker = Linker.nativeLinker();
        SymbolLookup stdlib = linker.defaultLookup();
        MemorySegment addr = stdlib.find("strlen").orElseThrow();
        System.out.println("strlen address found: " + addr);
    }
}

Describing the Signature

A FunctionDescriptor describes the C signature in terms of layouts. For size_t strlen(const char*) the return is a long and the argument is a pointer (ADDRESS).

import java.lang.foreign.*;

public class Main {
    public static void main(String[] args) {
        FunctionDescriptor desc = FunctionDescriptor.of(
            ValueLayout.JAVA_LONG,   // return: size_t
            ValueLayout.ADDRESS);    // arg: const char*
        System.out.println("Descriptor: " + desc);
    }
}

Building the Handle

Combine the symbol and descriptor with downcallHandle to get a MethodHandle you can invoke like any Java method.

import java.lang.foreign.*;
import java.lang.invoke.MethodHandle;

public class Main {
    public static void main(String[] args) {
        Linker linker = Linker.nativeLinker();
        MethodHandle strlen = linker.downcallHandle(
            linker.defaultLookup().find("strlen").orElseThrow(),
            FunctionDescriptor.of(ValueLayout.JAVA_LONG, ValueLayout.ADDRESS));
        System.out.println("Handle ready: " + strlen.type());
    }
}

Invoking the Function

To call strlen you pass a pointer to a native string. Allocate the string in an arena, then invoke the handle. The result comes back as a Java long.

import java.lang.foreign.*;
import java.lang.invoke.MethodHandle;

public class Main {
    public static void main(String[] args) throws Throwable {
        Linker linker = Linker.nativeLinker();
        MethodHandle strlen = linker.downcallHandle(
            linker.defaultLookup().find("strlen").orElseThrow(),
            FunctionDescriptor.of(ValueLayout.JAVA_LONG, ValueLayout.ADDRESS));
        try (Arena arena = Arena.ofConfined()) {
            MemorySegment str = arena.allocateUtf8String("Hello, FFM");
            long len = (long) strlen.invoke(str);
            System.out.println("Length = " + len);
        }
    }
}

Mapping Types

Each C type maps to a layout:

  • int to ValueLayout.JAVA_INT
  • long/size_t to JAVA_LONG
  • double to JAVA_DOUBLE
  • any pointer to ADDRESS

Getting these right is essential or the call corrupts data.

Functions Returning Pointers

When a C function returns a pointer, the handle returns a zero-length MemorySegment. To read past its start you must reinterpret it to the correct size with reinterpret(byteSize).

Passing Many Arguments

FunctionDescriptor.of(returnLayout, arg1, arg2, ...) lists arguments in order. For a void function use FunctionDescriptor.ofVoid(args...) with no return layout.

import java.lang.foreign.*;

public class Main {
    public static void main(String[] args) {
        // int (*)(const char*, int)
        FunctionDescriptor two = FunctionDescriptor.of(
            ValueLayout.JAVA_INT, ValueLayout.ADDRESS, ValueLayout.JAVA_INT);
        // void (*)(int)
        FunctionDescriptor noReturn = FunctionDescriptor.ofVoid(ValueLayout.JAVA_INT);
        System.out.println(two + " / " + noReturn);
    }
}

Handle Errors with throws

Because MethodHandle.invoke declares throws Throwable, your calling method must handle or declare it. This is why the examples declare throws Throwable.

Caching the Handle

Building a downcall handle is relatively expensive, so do it once and reuse it. A common pattern is to bind the handle in a static final field during class initialization and invoke it many times.

The handle itself is thread-safe to call concurrently.

Quick Check

Recall how a C pointer argument is described.

Recap

You learned to call native functions:

  • Linker.nativeLinker() plus a SymbolLookup to find symbols
  • FunctionDescriptor describes the signature with layouts
  • downcallHandle yields a MethodHandle you invoke
  • Pointers map to ADDRESS; invoke throws Throwable

Next: describing complex native data with layouts and structs.

Frequently asked questions

Is the “Downcall Handles” lesson free?

Yes — the full text of “Downcall Handles” is free to read here on the web, and the Java Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Java Academy course, upgrade to CoddyKit PRO.

What will I learn in “Downcall Handles”?

Call native functions. You practise Java Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Java Academy?

No prior experience is required. Java Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Downcall Handles” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Java Academy lesson?

Yes. Every Java Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Why FFM over JNI
  2. MemorySegment and Arena
  3. Downcall Handles
  4. Layouts and Structs
← Back to Java Academy