Skip to content

Sample for making jars with dylibs #180

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Nov 19, 2024
Merged
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: 10 additions & 0 deletions Plugins/JExtractSwiftPlugin/JExtractSwiftPlugin.swift
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,16 @@ struct JExtractSwiftBuildToolPlugin: BuildToolPlugin {
// Note: Target doesn't have a directoryURL counterpart to directory,
// so we cannot eliminate this deprecation warning.
let sourceDir = target.directory.string

let t = target.dependencies.first!
switch (t) {
case .target(let t):
t.sourceModule
case .product(let p):
p.sourceModules
@unknown default:
fatalError("Unknown target dependency type: \(t)")
}

let toolURL = try context.tool(named: "JExtractSwiftTool").url
let configuration = try readConfiguration(sourceDir: "\(sourceDir)")
Expand Down
23 changes: 23 additions & 0 deletions Samples/SwiftAndJavaJarSampleLib/Example.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2024 Apple Inc. and the Swift.org project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of Swift.org project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//

import com.example.swift.MySwiftLibrary;

public class Example {

public static void main(String[] args) {
MySwiftLibrary.helloWorld();
}

}
77 changes: 77 additions & 0 deletions Samples/SwiftAndJavaJarSampleLib/Package.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
// swift-tools-version: 6.0
// The swift-tools-version declares the minimum version of Swift required to build this package.

import CompilerPluginSupport
import PackageDescription

import class Foundation.FileManager
import class Foundation.ProcessInfo

// Note: the JAVA_HOME environment variable must be set to point to where
// Java is installed, e.g.,
// Library/Java/JavaVirtualMachines/openjdk-21.jdk/Contents/Home.
func findJavaHome() -> String {
if let home = ProcessInfo.processInfo.environment["JAVA_HOME"] {
return home
}

// This is a workaround for envs (some IDEs) which have trouble with
// picking up env variables during the build process
let path = "\(FileManager.default.homeDirectoryForCurrentUser.path()).java_home"
if let home = try? String(contentsOfFile: path, encoding: .utf8) {
if let lastChar = home.last, lastChar.isNewline {
return String(home.dropLast())
}

return home
}

fatalError("Please set the JAVA_HOME environment variable to point to where Java is installed.")
}
let javaHome = findJavaHome()

let javaIncludePath = "\(javaHome)/include"
#if os(Linux)
let javaPlatformIncludePath = "\(javaIncludePath)/linux"
#elseif os(macOS)
let javaPlatformIncludePath = "\(javaIncludePath)/darwin"
#else
// TODO: Handle windows as well
#error("Currently only macOS and Linux platforms are supported, this may change in the future.")
#endif

let package = Package(
name: "SwiftAndJavaJarSampleLib",
platforms: [
.macOS(.v10_15)
],
products: [
.library(
name: "MySwiftLibrary",
type: .dynamic,
targets: ["MySwiftLibrary"]
),

],
dependencies: [
.package(name: "swift-java", path: "../../"),
],
targets: [
.target(
name: "MySwiftLibrary",
dependencies: [
.product(name: "SwiftKitSwift", package: "swift-java"),
],
exclude: [
"swift-java.config",
],
swiftSettings: [
.swiftLanguageMode(.v5),
.unsafeFlags(["-I\(javaIncludePath)", "-I\(javaPlatformIncludePath)"])
],
plugins: [
.plugin(name: "JExtractSwiftPlugin", package: "swift-java"),
]
),
]
)
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2024 Apple Inc. and the Swift.org project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of Swift.org project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//

// This is a "plain Swift" file containing various types of declarations,
// that is exported to Java by using the `jextract-swift` tool.
//
// No annotations are necessary on the Swift side to perform the export.

#if os(Linux)
import Glibc
#else
import Darwin.C
#endif

public func helloWorld() {
p("\(#function)")
}

public func globalTakeInt(i: Int) {
p("i:\(i)")
}

public func globalTakeIntInt(i: Int, j: Int) {
p("i:\(i), j:\(j)")
}

public func globalCallMeRunnable(run: () -> ()) {
run()
}

public class MySwiftClass {

public var len: Int
public var cap: Int

public init(len: Int, cap: Int) {
self.len = len
self.cap = cap

p("\(MySwiftClass.self).len = \(self.len)")
p("\(MySwiftClass.self).cap = \(self.cap)")
let addr = unsafeBitCast(self, to: UInt64.self)
p("initializer done, self = 0x\(String(addr, radix: 16, uppercase: true))")
}

deinit {
let addr = unsafeBitCast(self, to: UInt64.self)
p("Deinit, self = 0x\(String(addr, radix: 16, uppercase: true))")
}

public var counter: Int32 = 0

public func voidMethod() {
p("")
}

public func takeIntMethod(i: Int) {
p("i:\(i)")
}

public func echoIntMethod(i: Int) -> Int {
p("i:\(i)")
return i
}

public func makeIntMethod() -> Int {
p("make int -> 12")
return 12
}

public func makeRandomIntMethod() -> Int {
return Int.random(in: 1..<256)
}
}

// ==== Internal helpers

private func p(_ msg: String, file: String = #fileID, line: UInt = #line, function: String = #function) {
print("[swift][\(file):\(line)](\(function)) \(msg)")
fflush(stdout)
}

#if os(Linux)
// FIXME: why do we need this workaround?
@_silgen_name("_objc_autoreleaseReturnValue")
public func _objc_autoreleaseReturnValue(a: Any) {}

@_silgen_name("objc_autoreleaseReturnValue")
public func objc_autoreleaseReturnValue(a: Any) {}
#endif
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"javaPackage": "com.example.swift"
}
Loading