Skip to content

Commit 6429f96

Browse files
committed
Prepare 2nd blog post for summer of code summary posts (2025)
These posts were approved by their respective contributor co-authors over here in #1191 also link to the android sdk blog post, since the screenshot there showcases this work Apply suggestions from code review
1 parent 20c6b4e commit 6429f96

File tree

2 files changed

+136
-0
lines changed

2 files changed

+136
-0
lines changed

_data/authors.yml

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -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
heckj:
564570
name: Joe Heck
565571
email: j_heck@apple.com
Lines changed: 130 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,130 @@
1+
---
2+
layout: new-layouts/post
3+
published: true
4+
date: 2025-02-NN 10:00:00
5+
title: 'Swift GSoC 2025 highlight: JNI mode for SwiftJava interoperability jextract tool
6+
author: [ktoso, mads]
7+
category: "Community"
8+
---
9+
10+
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 acomplished during the summer!
11+
12+
Summer of Code is an annual program, organized by Google, which provides hands-on experience for newcomers contributing
13+
to open source projects. Participants usually are students, but do not have to be.
14+
15+
In this series of four posts, we'll highlight each of the Summer of Code contributors and their projects.
16+
17+
- [Bringing Swiftly support to VS Code](2025-11-NN-swift-gsoc-2025-highlight-1-vscode-swiftly.md)
18+
- JNI mode for swift-java’s source jextract tool (this post)
19+
- [Improve the display of documentation during code completion in SourceKit-LSP](2025-11-NN-swift-gsoc-2025-highlight-3-vscode-swift-lsp-documentation.md)
20+
- [Improved Console Output for Swift Testing](2025-11-NN-swift-gsoc-2025-highlight-4-swift-testing-output.md)
21+
22+
---
23+
24+
## JNI mode for SwiftJava interoperability jextract tool
25+
26+
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.
27+
28+
# Overview
29+
30+
> 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/)!
31+
32+
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.
33+
34+
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!
35+
36+
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.
37+
38+
```bash
39+
swift-java jextract --swift-module MySwiftLibrary \
40+
--mode jni \
41+
--input-swift Sources/MySwiftLibrary \
42+
--output-java out/java \
43+
--output-swift out/swift
44+
```
45+
46+
# How does it work?
47+
48+
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:
49+
50+
```swift
51+
public class MySwiftClass {
52+
public let x: Int64
53+
public init(x: Int64) {
54+
self.x = x
55+
}
56+
57+
public func printMe() {
58+
print(“\(self.x)”);
59+
}
60+
}
61+
```
62+
63+
It is roughly generated to the equivalent Java `class`:
64+
65+
```java
66+
public final class MySwiftClass implements JNISwiftInstance {
67+
public static MySwiftClass init(long x, long y, SwiftArena swiftArena$) {
68+
return MySwiftClass.wrapMemoryAddressUnsafe(MySwiftClass.$init(x, y), swiftArena$);
69+
}
70+
71+
public long getX() {
72+
return MySwiftClass.$getX(this.$memoryAddress());
73+
}
74+
75+
public void printMe() {
76+
MySwiftClass.$printMe(this.$memoryAddress());
77+
}
78+
79+
private static native long $init(long x, long y);
80+
private static native long $getX(long self);
81+
private static native void $printMe(long self);
82+
}
83+
```
84+
We also generate additional Swift thunks that actually implement the `native` methods and call the underlying Swift methods.
85+
86+
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)!
87+
88+
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.
89+
90+
> 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)
91+
92+
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:
93+
```java
94+
public static MySwiftClass init(SwiftArena swiftArena$) {
95+
return MySwiftClass.wrapMemoryAddressUnsafe(MySwiftClass.$init(), swiftArena$);
96+
}
97+
private static native long $init();
98+
```
99+
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`.
100+
101+
`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:
102+
103+
1. `SwiftArena.ofConfined()`: returns a confined arena which is used with *try-with-resource*, to deallocate all instances at the end of some scope.
104+
2. `SwiftArena.ofAuto()`: returns an arena that deallocates instances once the garbage-collector has decided to do so.
105+
106+
This concept also exists in the FFM mode, and I recommend watching Konrad’s talk to learn more about them!
107+
108+
If we take a look at the native implementation of `$init` in Swift, we see how we allocate and initialize the memory:
109+
```swift
110+
// Generated code, not something you would write
111+
112+
@_cdecl("Java_com_example_swift_MySwiftClass__00024init__JJ")
113+
func Java_com_example_swift_MySwiftClass__00024init__JJ(environment: UnsafeMutablePointer<JNIEnv?>!, thisClass: jclass, x: jlong, y: jlong) -> jlong {
114+
let result$ = UnsafeMutablePointer<MySwiftClass>.allocate(capacity: 1)
115+
result$.initialize(to: MySwiftClass.init(x: Int64(fromJNI: x, in: environment!), y: Int64(fromJNI: y, in: environment!)))
116+
let resultBits$ = Int64(Int(bitPattern: result$))
117+
return resultBits$.getJNIValue(in: environment!)
118+
}
119+
```
120+
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\!
121+
122+
# My experience with GSoC
123+
124+
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\!
125+
126+
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.
127+
128+
---
129+
130+
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!

0 commit comments

Comments
 (0)