Sub topic 6
Finding native functions with SymbolLookup
This chapter assumes you know what a MemorySegment is and that you can read a C function signature. Before Java can call a native function, it needs the function's address. A SymbolLookup supplies that address.
What a lookup returns
SymbolLookup is a functional interface with one method:
Optional<MemorySegment> find(String name)If the symbol exists, you get a MemorySegment whose address is the start of that function or global variable. If it does not exist, you get an empty Optional. The method does not throw.
The segment has a size of zero, because a symbol name carries no length information. You cannot read or write through it. You pass it to a Linker to build a downcall handle, which later chapters cover.
Three sources of symbols
| Factory method | Searches | Typical use |
|---|---|---|
| `Linker.nativeLinker().defaultLookup()` | Commonly used libraries on the current platform, such as the C standard library | `strlen`, `qsort`, `getpid` |
| `SymbolLookup.loaderLookup()` | Libraries loaded by the calling class's class loader with `System.load` or `System.loadLibrary` | Your own library, loaded by name |
| `SymbolLookup.libraryLookup(name or path, arena)` | One specific library | A system library not covered by the default lookup |
The default lookup differs between operating systems. A function that resolves on Linux may be missing on Windows, so always handle the empty case.
Combining lookups
SymbolLookup.or(other) returns a lookup that tries the first one and then falls back to the second. This lets you build one search order and use it everywhere.
A runnable example
This program searches the loader lookup first, then the default lookup. It reports one symbol that exists and one that does not.
import java.lang.foreign.Linker;
import java.lang.foreign.MemorySegment;
import java.lang.foreign.SymbolLookup;
import java.util.Optional;
public class LookupDemo {
public static void main(String[] args) {
SymbolLookup lookup = SymbolLookup.loaderLookup()
.or(Linker.nativeLinker().defaultLookup());
for (String name : new String[] {"strlen", "no_such_function"}) {
Optional<MemorySegment> symbol = lookup.find(name);
if (symbol.isPresent()) {
System.out.println(name + " found, segment size " + symbol.get().byteSize());
} else {
System.out.println(name + " not found");
}
}
}
}The output is:
strlen found, segment size 0
no_such_function not foundLoading a specific library
When a function is not in the default lookup, open the library yourself. You must supply an Arena. Closing the arena unloads the library, so any address obtained from it becomes invalid.
import java.lang.foreign.Arena;
import java.lang.foreign.MemorySegment;
import java.lang.foreign.SymbolLookup;
public class LibraryDemo {
public static void main(String[] args) {
try (Arena arena = Arena.ofConfined()) {
// Linux library name. Use "libm.dylib" on macOS or a full Path on any system.
SymbolLookup libm = SymbolLookup.libraryLookup("libm.so.6", arena);
MemorySegment cos = libm.find("cos").orElseThrow();
System.out.println("cos is at address " + cos.address());
}
}
}If the library cannot be found, libraryLookup throws IllegalArgumentException. A missing symbol inside a found library still gives an empty Optional.
Common errors
- Calling
.get()on theOptionalwithout checking it. UseorElseThrow()with a clear message when the symbol is required. - Misspelling the name. Lookups are exact and case-sensitive, and C++ names are mangled, so expose a plain
extern "C"function. - Assuming
defaultLookup()contains every system library. It does not. - Using
loaderLookup()before callingSystem.loadLibrary. It then finds nothing.
Exercise
Your program calls SymbolLookup.loaderLookup().find("my_add"), and the result is empty even though libmyadd.so is on disk. What is the most likely cause, and what are two ways to fix it?
Show answer
The library was never loaded by the calling class's class loader. Call System.loadLibrary("myadd") (or System.load with a full path) before the lookup, or skip the loader and use SymbolLookup.libraryLookup("libmyadd.so", arena) with an arena that stays open while you use the function.