LOBs, SQL Escapes, Multiple Results and Generated Keys in JDBC
Store and read large binary and text data with Blob, Clob and streams, use JDBC escape syntax for dates, functions, outer joins, LIKE and stored procedure calls with CallableStatement, process multiple results with getMoreResults, and retrieve auto-generated keys.
kvi5hnuCode Sprout team member10 min readOn this page
Article 60 covered the everyday work of prepared statements. This article collects four more specialized query features: large objects for images, documents and long texts, the JDBC escape syntax that the driver translates into each database's dialect, statements that produce several results, and retrieving keys that the database generates for new rows.
Large objects
Besides numbers, strings and dates, databases can store large objects (LOBs): BLOBs (binary large objects) for images, PDFs or other files, and CLOBs (character large objects) for long texts. The SQL type names vary: BLOB/CLOB in the standard and in Oracle, H2 and Db2, BYTEA/TEXT in PostgreSQL, LONGBLOB/LONGTEXT in MySQL, VARBINARY(MAX)/NVARCHAR(MAX) in SQL Server.
Writing LOBs
The simplest way works for any reasonable size: bind a stream with setBinaryStream(index, in, length) or setCharacterStream(index, reader, length). The driver reads the stream while executing, so the whole object never has to be in memory at once. For small values, setBytes and setString work too.
Alternatively, create an empty LOB with conn.createBlob() or createClob(), fill it through setBinaryStream(pos), setBytes(pos, bytes), setCharacterStream(pos) or setString(pos, text), and bind it with setBlob or setClob.
Reading LOBs
rs.getBlob(column) and rs.getClob(column) return a Blob or Clob object. Depending on the driver, it may be just a handle, with the data fetched as you read:
Blob:length(),getBytes(pos, len),getBinaryStream(),getBinaryStream(pos, len),position(pattern, start)Clob:length(),getSubString(pos, len),getCharacterStream(),position(searchString, start)
Positions in LOBs start at 1, like column indexes. A LOB object can hold resources on the server, and is often valid only until the transaction ends. Call free() when you're done with it. For small values, rs.getBytes, rs.getString or rs.getBinaryStream(column) are simpler and avoid LOB objects altogether.
The JDK contains serializable, in-memory implementations, javax.sql.rowset.serial.SerialBlob and SerialClob, which are handy for tests and for disconnected row sets (article 63).
Generated keys
Tables often have a key the database generates: an identity column (GENERATED ALWAYS AS IDENTITY in standard SQL, SERIAL in older PostgreSQL code, AUTO_INCREMENT in MySQL) or a value from a sequence. After inserting a row, you usually need that key, for example to insert the row's children. Ask for it when you prepare the statement:
try (PreparedStatement ps = conn.prepareStatement(
"INSERT INTO orders (customer_id, placed) VALUES (?, ?)", Statement.RETURN_GENERATED_KEYS)) {
...
ps.executeUpdate();
try (ResultSet keys = ps.getGeneratedKeys()) {
if (keys.next()) orderId = keys.getLong(1);
}
}
RETURN_GENERATED_KEYS lets the driver decide which columns to return. Some drivers return all columns, and some only the identity column. To be precise, pass the column names, prepareStatement(sql, new String[] { "id" }), or column indexes. That also works for other values the database fills in, such as default timestamps. The same options exist for Statement.executeUpdate(sql, ...) and execute(sql, ...).
PostgreSQL, H2, SQLite and newer MariaDB versions also support INSERT ... RETURNING id, which you run with executeQuery like a SELECT. (The PostgreSQL driver implements getGeneratedKeys with exactly that.)
LOBs and keys with H2
This program stores a 100,000-byte image and an 80,000-character manual through streams, and a second row through createBlob and createClob. It retrieves the generated keys both ways, then reads the LOBs back as objects, streams and plain values:
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.sql.*;
import java.util.*;
public class Lobs {
public static void main(String[] args) throws Exception {
try (Connection conn = DriverManager.getConnection("jdbc:h2:mem:shop")) {
try (Statement stat = conn.createStatement()) {
stat.executeUpdate("""
CREATE TABLE product_media (
id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
product VARCHAR(40),
photo BLOB,
manual CLOB,
added TIMESTAMP DEFAULT CURRENT_TIMESTAMP)""");
}
byte[] photo = new byte[100_000];
for (int i = 0; i < photo.length; i++) photo[i] = (byte) (i * 31);
String manual = "Step 1: unpack.\n".repeat(5_000);
System.out.println("--- writing LOBs and getting the generated key ---");
try (PreparedStatement ps = conn.prepareStatement(
"INSERT INTO product_media (product, photo, manual) VALUES (?, ?, ?)", Statement.RETURN_GENERATED_KEYS)) {
ps.setString(1, "Oak shelf");
ps.setBinaryStream(2, new ByteArrayInputStream(photo), photo.length); // streams: no full copy needed
ps.setCharacterStream(3, new StringReader(manual), manual.length());
ps.executeUpdate();
try (ResultSet keys = ps.getGeneratedKeys()) {
while (keys.next()) System.out.println("generated key: " + keys.getInt(1));
}
}
try (PreparedStatement ps = conn.prepareStatement(
"INSERT INTO product_media (product, photo, manual) VALUES (?, ?, ?)", new String[] { "ID", "ADDED" })) {
Blob blob = conn.createBlob();
try (OutputStream out = blob.setBinaryStream(1)) { out.write(new byte[] { 1, 2, 3 }); }
Clob clob = conn.createClob();
clob.setString(1, "Short manual");
ps.setString(1, "Desk lamp");
ps.setBlob(2, blob);
ps.setClob(3, clob);
ps.executeUpdate();
blob.free();
clob.free();
try (ResultSet keys = ps.getGeneratedKeys()) {
ResultSetMetaData m = keys.getMetaData();
while (keys.next()) System.out.println("generated: " + m.getColumnLabel(1) + "=" + keys.getInt(1)
+ ", " + m.getColumnLabel(2) + " is a " + keys.getObject(2).getClass().getSimpleName());
}
}
System.out.println("--- reading LOBs ---");
try (Statement stat = conn.createStatement();
ResultSet rs = stat.executeQuery("SELECT id, product, photo, manual FROM product_media ORDER BY id")) {
while (rs.next()) {
Blob blob = rs.getBlob("photo");
Clob clob = rs.getClob("manual");
byte[] first = blob.getBytes(1, 3); // positions start at 1
long sum = 0;
try (InputStream in = blob.getBinaryStream()) {
int b; while ((b = in.read()) != -1) sum += b;
}
String start = clob.getSubString(1, Math.min(15, (int) clob.length()));
long lines;
try (BufferedReader r = new BufferedReader(clob.getCharacterStream())) { lines = r.lines().count(); }
System.out.printf("%d %s: photo %d bytes, first %s, byte sum %d; manual %d chars, %d lines, starts \"%s\"%n",
rs.getInt("id"), rs.getString("product"), blob.length(), Arrays.toString(first), sum, clob.length(), lines, start);
blob.free();
clob.free();
}
}
try (Statement stat = conn.createStatement();
ResultSet rs = stat.executeQuery("SELECT photo, manual FROM product_media WHERE id = 2")) {
rs.next();
System.out.println("as bytes/string: " + rs.getBytes(1).length + " bytes, \"" + rs.getString(2) + "\"");
}
}
}
}
Output with H2 2.3:
--- writing LOBs and getting the generated key ---
generated key: 1
generated: ID=2, ADDED is a Timestamp
--- reading LOBs ---
1 Oak shelf: photo 100000 bytes, first [0, 31, 62], byte sum 12749904; manual 80000 chars, 5000 lines, starts "Step 1: unpack."
2 Desk lamp: photo 3 bytes, first [1, 2, 3], byte sum 6; manual 12 chars, 1 lines, starts "Short manual"
as bytes/string: 3 bytes, "Short manual"
JDBC escape syntax
Databases agree on the core of SQL but differ in details: how to write a date literal, what a function is called, how outer joins or stored procedure calls look. JDBC defines an escape syntax in curly braces. The driver translates it into the native SQL of its database, and conn.nativeSQL(sql) shows the translation.
| Escape | Example | Meaning |
|---|---|---|
{d '...'}, {t '...'}, {ts '...'} | {d '2026-11-14'}, {ts '2026-11-14 09:30:00.5'} | date, time and timestamp literals in ISO format |
{fn name(args)} | {fn UCASE(name)}, {fn CONCAT(a, b)}, {fn CURDATE()} | scalar functions with standard names |
{oj ...} | {oj a LEFT OUTER JOIN b ON ...} | outer joins |
{escape 'c'} | name LIKE '%!_%' {escape '!'} | escape character for LIKE patterns |
{call proc(?, ?)}, {? = call func(?)} | {call archive_orders(?)} | stored procedure and function calls |
{limit n offset m} | {limit 10 offset 20} | row limits (JDBC 4.1) |
The JDBC specification lists the standard function names: string functions like UCASE, SUBSTRING and LOCATE, numeric ones like ABS and ROUND, date functions like CURDATE and TIMESTAMPADD, and system functions such as USER. DatabaseMetaData.getStringFunctions() and its relatives tell which ones a driver supports.
Today the escapes matter less than they once did. Date literals are best passed as parameters (setObject with a LocalDate), standard SQL outer joins and FETCH FIRST work almost everywhere, and code that needs to be truly portable usually goes through JPA or jOOQ. The call escape is still the normal way to call stored procedures.
This program prints each escaped query, its native translation and its result, and finally calls the built-in function UPPER through the {? = call ...} escape (explained in the next section):
import java.sql.*;
import java.util.*;
public class Escapes {
public static void main(String[] args) throws SQLException {
try (Connection conn = DriverManager.getConnection("jdbc:h2:mem:shop")) {
try (Statement stat = conn.createStatement()) {
stat.executeUpdate("CREATE TABLE products (id INTEGER PRIMARY KEY, product VARCHAR(40))");
stat.executeUpdate("INSERT INTO products VALUES (1, 'Oak shelf'), (2, 'Desk_lamp')");
}
for (String sql : List.of(
"SELECT {fn UCASE(product)}, {fn LENGTH(product)} FROM products WHERE id = 1",
"SELECT {d '2026-11-14'}, {t '09:30:00'}, {ts '2026-11-14 09:30:00.5'}",
"SELECT {fn CONCAT('a', 'b')}, {fn ABS(-3)}, {fn CURDATE()} IS NOT NULL",
"SELECT product FROM products WHERE product LIKE '%!_%' {escape '!'}",
"SELECT p.product FROM {oj products p LEFT OUTER JOIN products q ON p.id = q.id + 10}")) {
System.out.println(sql);
System.out.println(" native: " + conn.nativeSQL(sql));
try (Statement stat = conn.createStatement(); ResultSet rs = stat.executeQuery(sql)) {
int n = rs.getMetaData().getColumnCount();
while (rs.next()) {
var row = new ArrayList<String>();
for (int i = 1; i <= n; i++) row.add(rs.getString(i));
System.out.println(" " + row);
}
}
}
try (CallableStatement cs = conn.prepareCall("{? = call UPPER(?)}")) {
cs.registerOutParameter(1, Types.VARCHAR);
cs.setString(2, "hello");
cs.execute();
System.out.println("returned: " + cs.getString(1));
} catch (SQLException e) { System.out.println("call: " + e.getMessage()); }
}
}
}
Output with H2 2.3:
SELECT {fn UCASE(product)}, {fn LENGTH(product)} FROM products WHERE id = 1
native: SELECT UCASE(product) , LENGTH(product) FROM products WHERE id = 1
[OAK SHELF, 9]
SELECT {d '2026-11-14'}, {t '09:30:00'}, {ts '2026-11-14 09:30:00.5'}
native: SELECT d '2026-11-14' , t '09:30:00' , ts '2026-11-14 09:30:00.5'
[2026-11-14, 09:30:00, 2026-11-14 09:30:00.5]
SELECT {fn CONCAT('a', 'b')}, {fn ABS(-3)}, {fn CURDATE()} IS NOT NULL
native: SELECT CONCAT('a', 'b') , ABS(-3) , CURDATE() IS NOT NULL
[ab, 3, TRUE]
SELECT product FROM products WHERE product LIKE '%!_%' {escape '!'}
native: SELECT product FROM products WHERE product LIKE '%!_%' escape '!'
[Desk_lamp]
SELECT p.product FROM {oj products p LEFT OUTER JOIN products q ON p.id = q.id + 10}
native: SELECT p.product FROM products p LEFT OUTER JOIN products q ON p.id = q.id + 10
[Oak shelf]
[Desk_lamp]
returned: HELLO
H2 understands the escaped forms natively, so its translation mostly removes the braces. A driver for another database rewrites them more substantially. Statement.setEscapeProcessing(false) turns translation off for a statement.
Stored procedures and CallableStatement
A stored procedure is code that runs inside the database, written in a database-specific language such as PL/pgSQL, PL/SQL or T-SQL. You call it with a CallableStatement, a subclass of PreparedStatement:
try (CallableStatement cs = conn.prepareCall("{call order_total(?, ?)}")) {
cs.setLong(1, orderId); // IN parameter
cs.registerOutParameter(2, Types.DECIMAL); // OUT parameter: declare its type
cs.execute();
BigDecimal total = cs.getBigDecimal(2);
}
Input parameters are set as usual. Output parameters must be registered with their SQL type before executing and are read afterward with the getters. A parameter can be both (INOUT). A function's return value is written as {? = call func(?)}, where parameter 1 is the result. Since JDBC 3.0 (Java 1.4), parameters can also be set by name, cs.setLong("order_id", id), if the driver supports it. Procedures may also return result sets, which leads to the next topic.
Multiple results
Some statements produce more than one result: a stored procedure that runs several queries, or a batch of statements in one string (supported by SQL Server and PostgreSQL, and by MySQL with allowMultiQueries=true). The results come as a sequence. Each one is either a result set or an update count. Walk it with execute and getMoreResults:
boolean isResult = stat.execute(sql);
while (true) {
if (isResult) {
try (ResultSet rs = stat.getResultSet()) { ... }
} else {
int count = stat.getUpdateCount();
if (count == -1) break; // neither a result set nor an update count: the end
...
}
isResult = stat.getMoreResults();
}
execute and getMoreResults return true when the next result is a result set. When they return false, getUpdateCount either returns a count or -1, which means there are no more results. By default, getMoreResults closes the current result set. getMoreResults(Statement.KEEP_CURRENT_RESULT) keeps it open, if the driver supports that.
The program
The runnable demo uses the JDK's SerialBlob and SerialClob to exercise the Blob and Clob methods: lengths, 1-based positions, streams over ranges, searching with position, overwriting and truncating. Position 0 is rejected. The second part runs the multiple-results loop against a statement that behaves like a stored procedure producing a result set, two update counts and another result set. The statement is a dynamic proxy, and its result sets are CachedRowSets.
import java.io.*;
import java.lang.reflect.Proxy;
import java.nio.charset.StandardCharsets;
import java.sql.*;
import java.util.*;
import javax.sql.RowSetMetaData;
import javax.sql.rowset.*;
import javax.sql.rowset.serial.*;
public class Solution {
// ---------- a statement whose execute produces several results, like a stored procedure ----------
static ResultSet table(String column, String... values) throws SQLException {
CachedRowSet rs = RowSetProvider.newFactory().createCachedRowSet();
RowSetMetaData meta = new RowSetMetaDataImpl();
meta.setColumnCount(1);
meta.setColumnName(1, column);
meta.setColumnLabel(1, column);
meta.setColumnType(1, Types.VARCHAR);
rs.setMetaData(meta);
for (String v : values) { rs.moveToInsertRow(); rs.updateString(1, v); rs.insertRow(); }
rs.moveToCurrentRow();
rs.beforeFirst();
return rs;
}
static Statement procedureStatement(List<Object> results) {
var position = new int[] { -1 }; // index of the current result
return (Statement) Proxy.newProxyInstance(Statement.class.getClassLoader(), new Class<?>[] { Statement.class },
(proxy, method, args) -> {
Object current = position[0] >= 0 && position[0] < results.size() ? results.get(position[0]) : null;
return switch (method.getName()) {
case "execute", "getMoreResults" -> {
position[0]++;
yield position[0] < results.size() && results.get(position[0]) instanceof ResultSet;
}
case "getResultSet" -> current instanceof ResultSet rs ? rs : null;
case "getUpdateCount" -> current instanceof Integer n ? n : -1;
case "close" -> null;
default -> throw new SQLFeatureNotSupportedException(method.getName());
};
});
}
public static void main(String[] args) throws Exception {
System.out.println("--- Blob ---");
byte[] data = "PNG....image bytes....IEND".getBytes(StandardCharsets.US_ASCII);
Blob blob = new SerialBlob(data); // the JDK's own Blob implementation
System.out.println("length " + blob.length());
System.out.println("first 3 bytes (positions start at 1): " + new String(blob.getBytes(1, 3), StandardCharsets.US_ASCII));
System.out.println("position of IEND: " + blob.position("IEND".getBytes(StandardCharsets.US_ASCII), 1));
try (InputStream in = blob.getBinaryStream(8, 5)) {
System.out.println("stream of 5 bytes from 8: " + new String(in.readAllBytes(), StandardCharsets.US_ASCII));
}
blob.setBytes(1, "JPG".getBytes(StandardCharsets.US_ASCII));
blob.truncate(10);
System.out.println("after setBytes and truncate: " + new String(blob.getBytes(1, (int) blob.length()), StandardCharsets.US_ASCII));
try {
blob.getBytes(0, 1);
} catch (SQLException e) {
System.out.println("position 0: " + e.getClass().getSimpleName());
}
System.out.println("--- Clob ---");
Clob clob = new SerialClob("Step 1: unpack.\nStep 2: assemble.\nStep 3: enjoy.\n".toCharArray());
System.out.println("length " + clob.length() + ", chars 9-15: \"" + clob.getSubString(9, 7) + "\"");
System.out.println("\"Step 3\" at " + clob.position("Step 3", 1));
try (BufferedReader r = new BufferedReader(clob.getCharacterStream())) {
r.lines().map(l -> " line: " + l).forEach(System.out::println);
}
clob.setString(1, "STEP");
System.out.println("after setString: " + clob.getSubString(1, 15));
System.out.println("--- processing multiple results ---");
Statement stat = procedureStatement(List.of(
table("NAME", "Hammer", "Saw"), // a result set
3, // an update count
0, // another update count
table("SUPPLIER", "ACME"))); // another result set
boolean isResult = stat.execute("CALL monthly_report()");
while (true) {
if (isResult) {
try (ResultSet rs = stat.getResultSet()) {
String col = rs.getMetaData().getColumnLabel(1);
var values = new ArrayList<String>();
while (rs.next()) values.add(rs.getString(1));
System.out.println("result set " + col + " " + values);
}
} else {
int count = stat.getUpdateCount();
if (count == -1) break; // no more results
System.out.println("update count " + count);
}
isResult = stat.getMoreResults();
}
System.out.println("done");
}
}
--- Blob ---
length 26
first 3 bytes (positions start at 1): PNG
position of IEND: 23
stream of 5 bytes from 8: image
after setBytes and truncate: JPG....ima
position 0: SerialException
--- Clob ---
length 49, chars 9-15: "unpack."
"Step 3" at 35
line: Step 1: unpack.
line: Step 2: assemble.
line: Step 3: enjoy.
after setString: STEP 1: unpack.
--- processing multiple results ---
result set NAME [Hammer, Saw]
update count 3
update count 0
result set SUPPLIER [ACME]
done
Common questions
Should I store files in the database or on disk? Small files that change with the data (thumbnails, signatures, short documents) are fine in the database. Large or numerous files are usually better in an object store or file system, with the key in a table. Then you need to keep the two consistent yourself, for example by deleting files after the transaction that removed the row commits.
How do I read a large BLOB without running out of memory?
Use rs.getBinaryStream(column) and copy it to a file or the HTTP response with InputStream.transferTo. Don't call getBytes on huge values. With PostgreSQL's bytea, the driver reads the whole value anyway; its "large objects" API is needed for true streaming.
How do I get the ID of a row I just inserted?
prepareStatement(sql, new String[] {"id"}), then getGeneratedKeys() after executeUpdate. Or, where supported, INSERT ... RETURNING id with executeQuery. Don't use SELECT MAX(id): another transaction may insert at the same time.
Do I need stored procedures? Not usually. Most applications keep logic in Java and use plain SQL. Procedures make sense for data-heavy operations that would otherwise move lots of rows over the network, or when a database team provides them as the interface.
Does batch insert return generated keys?
Often, yes: prepare with key columns, call executeBatch, then getGeneratedKeys returns one row per inserted row. Support varies by driver; PostgreSQL, H2 and MySQL support it.
API reference
| API | Purpose |
|---|---|
PreparedStatement.setBinaryStream, setCharacterStream, setBlob, setClob, setBytes | write LOB data |
Connection.createBlob(), createClob() | create empty LOBs to fill |
ResultSet.getBlob, getClob, getBinaryStream, getCharacterStream, getBytes | read LOB data |
Blob.length, getBytes, getBinaryStream, setBytes, setBinaryStream, position, truncate, free | work with binary LOBs (positions start at 1) |
Clob.length, getSubString, getCharacterStream, setString, setCharacterStream, position, free | work with character LOBs |
javax.sql.rowset.serial.SerialBlob, SerialClob | in-memory LOB implementations |
prepareStatement(sql, RETURN_GENERATED_KEYS), (sql, columnNames), getGeneratedKeys() | retrieve generated keys |
Connection.nativeSQL(sql), Statement.setEscapeProcessing | see or disable escape translation |
Connection.prepareCall(sql), CallableStatement.registerOutParameter, getters | call stored procedures |
Statement.execute, getResultSet, getUpdateCount, getMoreResults | walk multiple results |
Summary
- BLOBs and CLOBs hold large binary and text data. Write them with streams or
createBlob/createClob, read them throughBlob/Clobobjects or streams, andfree()them. LOB positions start at 1. - Ask for generated keys when preparing an INSERT, preferably naming the key columns, and read them from
getGeneratedKeys(). Some databases also supportRETURNING. - JDBC escapes in braces (
{d ...},{fn ...},{oj ...},{escape ...},{call ...}) are translated into the database's dialect. CallableStatementcalls stored procedures with IN, OUT and INOUT parameters.- A statement can produce a sequence of result sets and update counts. Loop with
getMoreResultsuntilgetUpdateCount()returns -1.
Practice Questions
Why should you prefer setBinaryStream(index, in, length) over reading a 200 MB file into a byte array and calling setBytes?
setBytes needs the whole file in memory, which costs 200 MB of heap for every concurrent upload. With a stream, the driver reads and sends the data in pieces while it executes the statement, so memory use stays small. (Whether 200 MB files belong in the database at all is a separate question.)
You insert an order and then need its ID to insert the order lines. How do you get the ID that the database generated?
Prepare the INSERT with conn.prepareStatement(sql, new String[] { "id" }) (or Statement.RETURN_GENERATED_KEYS), execute it, and read the key from ps.getGeneratedKeys(). On databases that support it, INSERT ... RETURNING id with executeQuery works too. Don't use SELECT MAX(id), which breaks with concurrent inserts.
What does the driver do with SELECT * FROM orders WHERE placed \> {d '2026-01-01'}?
It translates the escape into the database's syntax for a date literal, such as DATE '2026-01-01' or a vendor-specific conversion function, before sending the SQL. conn.nativeSQL(sql) shows the result. Better still, bind the date as a parameter with setObject(1, LocalDate.of(2026, 1, 1)).
How do you call a stored function order_total(order_id) that returns a DECIMAL?
CallableStatement cs = conn.prepareCall("{? = call order_total(?)}"); cs.registerOutParameter(1, Types.DECIMAL); cs.setLong(2, orderId); cs.execute(); BigDecimal total = cs.getBigDecimal(1);. The return value is parameter 1, and its type must be registered before executing.
In the multiple-results loop, why isn't getMoreResults() == false enough to stop?
false only means the next result isn't a result set. It may still be an update count. The end is reached when getMoreResults() returns false and getUpdateCount() returns -1. Stopping at the first false would skip update counts and any result sets after them.
Previous: Prepared Statements in JDBC: Parameters, Reuse and Preventing SQL Injection
Related reading
- Prepared Statements in JDBC: Parameters, Reuse and Preventing SQL Injection
- Executing SQL with JDBC: Statements, Result Sets and SQL Exceptions
- Connecting to a Database with JDBC: URLs, Drivers, DriverManager and DataSource
- JDBC Design and SQL Basics: How Java Talks to Databases
- Sending Email from Java: SMTP and Jakarta Mail

More in Core Java II
FFM Upcalls, Variadic Functions and errno
Advanced FFM calls: passing Java code to C as function pointers with upcall stubs, binding objects and lambdas, calling variadic functions such as printf, capturing errno and GetLastError, and a C library that calls back into Java. The final article of the course.
Calling Foreign Functions: Linker, Symbol Lookup, Downcalls and jextract
Calling C functions from pure Java with the FFM API: the native linker, default, library and loader symbol lookups, function descriptors, downcall handles, invokeExact, pointers and NULL, struct results, critical calls, enabling native access, and generating bindings with jextract.
FFM Memory Layouts: Structs, Unions, Sequences and Var Handles
Describing C data with FFM memory layouts: value layouts and C types, struct and union layouts, alignment and padding, sequences, layout paths, var handles with base offsets, offset and slice handles, pointers with target layouts, and atomic access modes.
Foreign Function and Memory API: Arenas and Memory Segments
Getting started with the FFM API (final since Java 22): a first foreign call, confined, shared, automatic and global arenas, native and heap memory segments, reading and writing values, C strings and arrays, alignment and byte order, slices, copies, allocators, and memory-mapped files.
Discussion
Sign in to ask a question or share what you learned.