Skip to content

Commit e34ef73

Browse files
committed
[JavaKit] Add JNIEnvPointer for Android
1 parent 94d5f34 commit e34ef73

File tree

1 file changed

+20
-5
lines changed

1 file changed

+20
-5
lines changed

Sources/JavaKit/JavaKitVM/JavaVirtualMachine.swift

Lines changed: 20 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,11 @@ import Foundation
1919
#endif
2020

2121
public typealias JavaVMPointer = UnsafeMutablePointer<JavaVM?>
22+
#if canImport(Android)
23+
typealias JNIEnvPointer = UnsafeMutablePointer<JNIEnv?>
24+
#else
25+
typealias JNIEnvPointer = UnsafeMutableRawPointer
26+
#endif
2227

2328
public final class JavaVirtualMachine: @unchecked Sendable {
2429
/// The JNI version that we depend on.
@@ -61,7 +66,7 @@ public final class JavaVirtualMachine: @unchecked Sendable {
6166
) throws {
6267
self.classpath = classpath
6368
var jvm: JavaVMPointer? = nil
64-
var environment: UnsafeMutableRawPointer? = nil
69+
var environment: JNIEnvPointer? = nil
6570
var vmArgs = JavaVMInitArgs()
6671
vmArgs.version = JavaVirtualMachine.jniVersion
6772
vmArgs.ignoreUnrecognized = jboolean(ignoreUnrecognized ? JNI_TRUE : JNI_FALSE)
@@ -161,12 +166,18 @@ extension JavaVirtualMachine {
161166
return environment.assumingMemoryBound(to: JNIEnv?.self)
162167
}
163168

169+
#if canImport(Android)
170+
var jniEnv = environment?.assumingMemoryBound(to: JNIEnv?.self)
171+
#else
172+
var jniEnv = environment
173+
#endif
174+
164175
// Attach the current thread to the JVM.
165176
let attachResult: jint
166177
if asDaemon {
167-
attachResult = jvm.pointee!.pointee.AttachCurrentThreadAsDaemon(jvm, &environment, nil)
178+
attachResult = jvm.pointee!.pointee.AttachCurrentThreadAsDaemon(jvm, &jniEnv, nil)
168179
} else {
169-
attachResult = jvm.pointee!.pointee.AttachCurrentThread(jvm, &environment, nil)
180+
attachResult = jvm.pointee!.pointee.AttachCurrentThread(jvm, &jniEnv, nil)
170181
}
171182

172183
// If we failed to attach, report that.
@@ -175,9 +186,13 @@ extension JavaVirtualMachine {
175186
throw attachError
176187
}
177188

178-
JavaVirtualMachine.destroyTLS.set(environment!)
189+
JavaVirtualMachine.destroyTLS.set(jniEnv!)
179190

180-
return environment!.assumingMemoryBound(to: JNIEnv?.self)
191+
#if canImport(Android)
192+
return jniEnv!
193+
#else
194+
return jniEnv!.assumingMemoryBound(to: JNIEnv?.self)
195+
#endif
181196
}
182197

183198
/// Detach the current thread from the Java Virtual Machine. All Java

0 commit comments

Comments
 (0)