Skip to content

Commit 9f6d25f

Browse files
authored
[GSoC-2025] Blog post 2: JNI mode for Swift Java JExtract (#1211)
Prepare 2nd blog post for summer of code summary posts (2025)
1 parent 8ac0896 commit 9f6d25f

File tree

2 files changed

+131
-1
lines changed

2 files changed

+131
-1
lines changed

_data/authors.yml

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -202,7 +202,7 @@ ktoso:
202202
email: ktoso@apple.com
203203
github: ktoso
204204
gravatar: 03cb20b97f6a14701c24c4e088b6af87
205-
about: "Konrad Malawski is a member of a team developing foundational server-side Swift libraries at Apple, with focus on distributed systems and concurrency."
205+
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."
206206

207207
compnerd:
208208
name: Saleem Abdulrasool
@@ -560,6 +560,12 @@ mitchellallison:
560560
github: mitchellallison
561561
about: "Mitchell Allison works on Distributed Systems in Swift at Apple."
562562

563+
mads:
564+
name: Mads Odgaard
565+
email: mads@madsodgaard.com
566+
github: madsodgaard
567+
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.
568+
563569
priyambada:
564570
name: Priyambada Roul
565571
email: priyaroul99@gmail.com
Lines changed: 124 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,124 @@
1+
---
2+
layout: new-layouts/post
3+
published: true
4+
date: 2025-11-07 10:00:00
5+
title: "GSoC 2025 Showcase: Extending Swift-Java Interoperability"
6+
author: [mads, ktoso]
7+
category: "Community"
8+
---
9+
10+
This is the second post in our series showcasing the Swift community’s participation in [Google Summer of Code](https://summerofcode.withgoogle.com) 2025. Learn more about the projects and work accomplished:
11+
12+
- [Bringing Swiftly support to VS Code](/blog/gsoc-2025-showcase-swiftly-support-in-vscode/)
13+
- Extending Swift-Java Interoperability (this post)
14+
- Improved display of documentation during code completion in SourceKit-LSP _(coming soon)_
15+
- Improved Console Output for Swift Testing _(coming soon)_
16+
17+
Each GSoC contributor has shared a writeup about their project and experience in the program on the Swift forums. Today’s featured project improved interoperability between Swift and Java, contributed by Mads Odgaard. Mads recently presented on this project at the Server-Side Swift conference: [Expanding Swift/Java Interoperability](https://www.youtube.com/watch?v=tOH6V1IvTAc), and you may 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/)!
18+
19+
To learn more, you can read the [full post on the Swift forums](https://forums.swift.org/t/gsoc-2025-new-jni-mode-added-to-swift-java-jextract-tool/8185).
20+
21+
---
22+
23+
## JNI mode for SwiftJava interoperability jextract tool
24+
25+
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 Malawski for Google Summer of Code 2025.
26+
27+
# Overview
28+
29+
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.
30+
31+
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!
32+
33+
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.
34+
35+
```bash
36+
swift-java jextract --swift-module MySwiftLibrary \
37+
--mode jni \
38+
--input-swift Sources/MySwiftLibrary \
39+
--output-java out/java \
40+
--output-swift out/swift
41+
```
42+
43+
# How does it work?
44+
45+
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:
46+
47+
```swift
48+
public class MySwiftClass {
49+
public let x: Int64
50+
public init(x: Int64) {
51+
self.x = x
52+
}
53+
54+
public func printMe() {
55+
print(“\(self.x)”);
56+
}
57+
}
58+
```
59+
60+
It is roughly generated to the equivalent Java `class`:
61+
62+
```java
63+
public final class MySwiftClass implements JNISwiftInstance {
64+
public static MySwiftClass init(long x, long y, SwiftArena swiftArena$) {
65+
return MySwiftClass.wrapMemoryAddressUnsafe(MySwiftClass.$init(x, y), swiftArena$);
66+
}
67+
68+
public long getX() {
69+
return MySwiftClass.$getX(this.$memoryAddress());
70+
}
71+
72+
public void printMe() {
73+
MySwiftClass.$printMe(this.$memoryAddress());
74+
}
75+
76+
private static native long $init(long x, long y);
77+
private static native long $getX(long self);
78+
private static native void $printMe(long self);
79+
}
80+
```
81+
We also generate additional Swift thunks that actually implement the `native` methods and call the underlying Swift methods.
82+
83+
You can learn more about how the memory allocation and management works [in the full version of this post on the Swift forums](https://forums.swift.org/t/gsoc-2025-new-jni-mode-added-to-swift-java-jextract-tool/81858)!
84+
85+
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 handle the complexity of witness tables like FFM mode does.
86+
87+
> 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)
88+
89+
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:
90+
```java
91+
public static MySwiftClass init(SwiftArena swiftArena$) {
92+
return MySwiftClass.wrapMemoryAddressUnsafe(MySwiftClass.$init(), swiftArena$);
93+
}
94+
private static native long $init();
95+
```
96+
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`.
97+
98+
`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:
99+
100+
1. `SwiftArena.ofConfined()`: returns a confined arena which is used with *try-with-resource*, to deallocate all instances at the end of some scope.
101+
2. `SwiftArena.ofAuto()`: returns an arena that deallocates instances once the garbage-collector has decided to do so.
102+
103+
This concept also exists in the FFM mode, and I recommend watching [Konrad’s talk at
104+
try! Swift Tokyo 2025](https://www.youtube.com/watch?v=vgtzhTOhEbs) to learn more!
105+
106+
If we take a look at the native implementation of `$init` in Swift, we see how we allocate and initialize the memory:
107+
```swift
108+
// Generated code, not something you would write
109+
110+
@_cdecl("Java_com_example_swift_MySwiftClass__00024init__JJ")
111+
func Java_com_example_swift_MySwiftClass__00024init__JJ(environment: UnsafeMutablePointer<JNIEnv?>!, thisClass: jclass, x: jlong, y: jlong) -> jlong {
112+
let result$ = UnsafeMutablePointer<MySwiftClass>.allocate(capacity: 1)
113+
result$.initialize(to: MySwiftClass.init(x: Int64(fromJNI: x, in: environment!), y: Int64(fromJNI: y, in: environment!)))
114+
let resultBits$ = Int64(Int(bitPattern: result$))
115+
return resultBits$.getJNIValue(in: environment!)
116+
}
117+
```
118+
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!
119+
120+
# My experience with GSoC
121+
122+
Google Summer of Code was an awesome experience for me! I got to work with my favorite language on a library that is very relevant! A HUGE thanks to my mentor Konrad Malawski, who provided invaluable guidance, was always available for questions and allowed me to experiment and take ownership of the work!
123+
124+
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 what might seem to be embarrassing questions, they might actually turn out to be great questions and lead to useful discussions and solutions.

0 commit comments

Comments
 (0)