Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 8 additions & 2 deletions _data/authors.yml
Original file line number Diff line number Diff line change
Expand Up @@ -202,7 +202,7 @@ ktoso:
email: ktoso@apple.com
github: ktoso
gravatar: 03cb20b97f6a14701c24c4e088b6af87
about: "Konrad Malawski is a member of a team developing foundational server-side Swift libraries at Apple, with focus on distributed systems and concurrency."
about: "Konrad is part of the Swift language team and Swift on Server Workgroup, where he works on language and runtime features with particular interest in supporting server and distributed computing use-cases, and expanding the Swift ecosystem."

compnerd:
name: Saleem Abdulrasool
Expand Down Expand Up @@ -560,6 +560,12 @@ mitchellallison:
github: mitchellallison
about: "Mitchell Allison works on Distributed Systems in Swift at Apple."

mads:
name: Mads Odgaard
email: mads@madsodgaard.com
github: madsodgaard
about: Mads is a Tech Lead at Frameo. During Google Summer of Code 2025, he worked on bringing JNI support to the jextract tool which is part of the Swift Java interoperability project.

heckj:
name: Joe Heck
email: j_heck@apple.com
Expand All @@ -571,4 +577,4 @@ davelester:
name: Dave Lester
github: davelester
gravatar: "376decb8be2d1c50df06daf50ef3b6b5"
about: "Dave Lester is a Senior Product Manager at Apple and member of the Swift website workgroup."
about: "Dave Lester is a Senior Product Manager at Apple and member of the Swift website workgroup."
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
---
layout: new-layouts/post
published: true
date: 2025-02-NN 10:00:00
title: "Swift GSoC 2025 highlight: JNI mode for SwiftJava interoperability jextract tool"
author: [ktoso, mads]
category: "Developer Tools"
---

Another year of successful Swift participation in [Google Summer of Code](https://summerofcode.withgoogle.com) 2025 came to an end recently, and this year we'd like to shine some light on the projects and work accomplished during the summer!

Summer of Code is an annual program, organized by Google, which provides hands-on experience for newcomers contributing
to open source projects. Participants usually are students, but do not have to be.

In this series of four posts, we'll highlight each of the Summer of Code contributors and their projects.

- [Bringing Swiftly support to VS Code](2025-11-NN-swift-gsoc-2025-highlight-1-vscode-swiftly.md)
- JNI mode for swift-java’s source jextract tool (this post)
- [Improve the display of documentation during code completion in SourceKit-LSP](2025-11-NN-swift-gsoc-2025-highlight-3-vscode-swift-lsp-documentation.md)
- [Improved Console Output for Swift Testing](2025-11-NN-swift-gsoc-2025-highlight-4-swift-testing-output.md)

---

## JNI mode for SwiftJava interoperability jextract tool

My name is Mads and I am excited to share with you what I have been working on for Swift/Java interoperability over the summer with my mentor Konrad for Google Summer of Code 2025.

# Overview

> You can also view Mads' presentation from the Serverside.swift conference about his work on this project: [Expanding Swift/Java Interoperability](https://www.youtube.com/watch?v=tOH6V1IvTAc). You may also have noticed it in action in the recent Swift.org blog post: [Announcing the Swift SDK for Android](https://www.swift.org/blog/nightly-swift-sdk-for-android/)!

The [swift-java](https://github.com/swiftlang/swift-java) interoperability library provides the `swift-java jextract` tool, which automatically generates Java sources that are used to call Swift code from Java. Previously, this tool only worked using the [Foreign Function and Memory API (FFM)](https://docs.oracle.com/en/java/javase/21/core/foreign-function-and-memory-api.html), which requires JDK 22+, making it unavailable on platforms such as Android. The goal of this project was to extend the jextract tool, such that it is able to generate Java sources using JNI instead of FFM and thereby allowing more platforms to utilize Swift/Java interoperability.

I am very glad to report that we have succeeded in that goal, supporting even more features than initially planned! Our initial goal was to achieve feature parity with the FFM mode, but the new JNI mode also supports additional Swift language features such as enums and protocols!

With the outcome of this project, you can now run the following command to automatically generate Java wrappers for your Swift library using JNI, therefore opening up the possibility of using it on platforms such as Android.

```bash
swift-java jextract --swift-module MySwiftLibrary \
--mode jni \
--input-swift Sources/MySwiftLibrary \
--output-java out/java \
--output-swift out/swift
```

# How does it work?

Each Swift class/struct is extracted as a single Java `class`. Functions and variables are generated as Java methods, that internally calls down to a native method that is implemented in Swift using `@_cdecl`. Take a look at the following example:

```swift
public class MySwiftClass {
public let x: Int64
public init(x: Int64) {
self.x = x
}

public func printMe() {
print(“\(self.x)”);
}
}
```

It is roughly generated to the equivalent Java `class`:

```java
public final class MySwiftClass implements JNISwiftInstance {
public static MySwiftClass init(long x, long y, SwiftArena swiftArena$) {
return MySwiftClass.wrapMemoryAddressUnsafe(MySwiftClass.$init(x, y), swiftArena$);
}

public long getX() {
return MySwiftClass.$getX(this.$memoryAddress());
}

public void printMe() {
MySwiftClass.$printMe(this.$memoryAddress());
}

private static native long $init(long x, long y);
private static native long $getX(long self);
private static native void $printMe(long self);
}
```
We also generate additional Swift thunks that actually implement the `native` methods and call the underlying Swift methods.

You can learn more about how the memory allocation and management works [in the full version of this post of this post on the Swift forums](https://forums.swift.org/t/gsoc-2025-new-jni-mode-added-to-swift-java-jextract-tool/81858)!

An interesting aspect of an interoperability library such as `swift-java` is the memory management between the two sides, in this case the JVM and Swift. The FFM mode uses the FFM APIs around `MemorySegment` to allocate and manage native memory. We are not so lucky in JNI. In older Java versions there are different ways of allocating memory, such as `Unsafe` or `ByteBuffer.allocateDirect()`. We could have decided to use these and allocate memory on the Java side, like FFM, but instead we decided to move the responsibility to Swift, which allocates the memory instead. This had some nice upsides, as we did not have to mess the the witness tables like FFM does.

> For more info on memory in FFM, I strongly recommend watching Konrad’s talk [try! Swift Tokyo 2025 - Foreign Function and Memory APIs and Swift/Java interoperability](https://www.youtube.com/watch?v=vgtzhTOhEbs)

The most obvious place we need to allocate memory is when we initialize a wrapped Swift `class`. Take a look at the following generated code for a Swift initializer:
```java
public static MySwiftClass init(SwiftArena swiftArena$) {
return MySwiftClass.wrapMemoryAddressUnsafe(MySwiftClass.$init(), swiftArena$);
}
private static native long $init();
```
Here we see that we are calling a native method `$init` which returns a `long`. This value is a pointer to the Swift instance in the memory space of Swift. It is passed to `wrapMemoryAddressUnsafe`, which is basically just storing the pointer in a local field and registering the wrapper to the `SwiftArena`.

`SwiftArena` is a type that is used to ensure we eventually deallocate the memory when the Java wrapper is no longer needed. There exists two implements of this:

1. `SwiftArena.ofConfined()`: returns a confined arena which is used with *try-with-resource*, to deallocate all instances at the end of some scope.
2. `SwiftArena.ofAuto()`: returns an arena that deallocates instances once the garbage-collector has decided to do so.

This concept also exists in the FFM mode, and I recommend watching Konrad’s talk to learn more about them!

If we take a look at the native implementation of `$init` in Swift, we see how we allocate and initialize the memory:
```swift
// Generated code, not something you would write

@_cdecl("Java_com_example_swift_MySwiftClass__00024init__JJ")
func Java_com_example_swift_MySwiftClass__00024init__JJ(environment: UnsafeMutablePointer<JNIEnv?>!, thisClass: jclass, x: jlong, y: jlong) -> jlong {
let result$ = UnsafeMutablePointer<MySwiftClass>.allocate(capacity: 1)
result$.initialize(to: MySwiftClass.init(x: Int64(fromJNI: x, in: environment!), y: Int64(fromJNI: y, in: environment!)))
let resultBits$ = Int64(Int(bitPattern: result$))
return resultBits$.getJNIValue(in: environment!)
}
```
We are basically allocating memory for a single instance of `MySwiftClass`, initializing it to a new instance and returning the memory address of the pointer. It is the same approach for `struct` as well!

# My experience with GSoC

Google Summer of Code was an awesome experience for me! I got to work with my favourite language on a library that is very relevant! A **HUGE** thanks to my mentor @ktoso, who provided invaluable guidance, was always available for questions and allowed me to experiment and take ownership of the work!

I would definitely recommend GSoC to anyone interested, it is a great way to engage with the open-source community, develop your skills and work with some talented people! My number one advice would be to never be afraid of asking seemingly “stupid” questions, they might not be that stupid afterall.

---

If you'd like to learn more about this project, please [check out the full post on the Swift forums](https://forums.swift.org/t/gsoc-2025-new-jni-mode-added-to-swift-java-jextract-tool/81858) as it contains lots of more additional examples and in-depth discussion about memory management and trade-offs this project had to resolve!