Call a program written in Swift from Processing (Java)

When I make utility software using Processing, I can't get to the itchy place (system environment setting system, etc.)

If you implement it in Swift, you will not have a hard time hitting the API, but I feel that using Runtime # exec or ProcessBuilder on the Java side is something different, so Somehow I want to hit a function implemented in Swift like a method implemented in Java!

JNA(Java Native Access) Since the substance of Processing is a Java class that inherits the PApplet class, Java grammar and assets can be used

Java has a mechanism called JNI (Java Native Interface) that links with native code implemented in C / C ++. I think that if you use this JNI, you can call the native code implemented in Swift, It is really impossible to write JNI that connects Java and C / C ++ (Create a function with a function name including the package name ...)

Ah, ** I want to call native code from Java ** But ** I don't want to write JNI **

In such a case, use ** JNA (Java Native Access) ** It seems that he will do something good!

For JNA, refer to this area. https://qiita.com/everylittle/items/b888cbec643f14de5ea6

Generate dynamic link library from Swift source

Create the method you want to call from Java, both in the rabbit and in the corner

hello.swift


import Darwin.C

@_cdecl("hello")
public func hello() {
    print("Hello")
    fflush(stdout)
}

The above program implements a function that displays Hello on standard output The point is ** 1. Set the calling convention **, ** 2. Make it public **

It seems that it will not be printed without fflush (stdout), so let's put it in Printf from native code appears only at the end of the java app https://stackoverrun.com/ja/q/3379588

Let's compile it as it is the source as it is Generate a dynamic link library (lib * .dylib on MacOS) from the above program

Generate dynamic link library


swiftc -emit-library hello.swift

If you execute the above command in the terminal, it will be lib + filename (without extension) + .dylib A dynamic link library is generated image.png

If you check with the nm command, it seems that the hello function is in the global section and you can call it something.

Confirm with nm command


cha84rakanal$ nm libhello.dylib 
0000000000000e40 T _$S5helloAAyyF
                 U _$S6Darwin6stdoutSpySo7__sFILEVGvg
                 U _$SSS21_builtinStringLiteral17utf8CodeUnitCount7isASCIISSBp_BwBi1_tcfC
                 U _$SSSN
                 U _$Ss27_allocateUninitializedArrayySayxG_BptBwlFyp_Tg5
                 U _$Ss5print_9separator10terminatoryypd_S2StF
                 U _$Ss5print_9separator10terminatoryypd_S2StFfA0_
                 U _$Ss5print_9separator10terminatoryypd_S2StFfA1_
0000000000000fac s ___swift_reflection_version
                 U __swift_FORCE_LOAD_$_swiftDarwin
0000000000001060 s __swift_FORCE_LOAD_$_swiftDarwin_$_hello
                 U _fflush
0000000000000e30 T _hello
                 U _swift_bridgeObjectRelease
                 U _swift_bridgeObjectRetain
                 U dyld_stub_binder
cha84rakanal$ 

Actually call the function implemented in Swift from the Java side

Now, let's actually call the Hello function created earlier from the Processing (Java) side. Put the dynamically generated dynamic link library in the data directory of the sketch and move it with the next sketch!

JNAProcessing.pde


import com.sun.jna.Library;
import com.sun.jna.Native;
import com.sun.jna.Platform;

public interface SwiftLib extends Library {
    void hello();
}

SwiftLib mylib;

void setup(){
    mylib = (SwiftLib) Native.loadLibrary(dataPath("libhello.dylib"), SwiftLib.class);
    mylib.hello();
}

void draw(){
}

The point is

  1. Import JNA related libraries
  2. Define an interface that inherits com.sun.jna.Library (definition of the function created inside)
  3. Load the dynamic link library with Native # loadLibrary, and if you only use the library name, go to the path of the dynamic library referenced by Java, and be sure to enter it with an absolute path.

If Hello is displayed, it's OK! All you have to do is implement whatever you like in Swift! Well then, good Processing Life

image.png

Recommended Posts

Call a program written in Swift from Processing (Java)
Call a C function from Swift
Call Java method from JavaScript executed in Java
I made a primality test program in Java
GetInstance () from a @Singleton class in Groovy from Java
Java method call from RPG (method call in own class)
I wrote a primality test program in Java
I wrote a prime factorization program in Java
Call Java from JRuby
Call a method with a Kotlin callback block from Java
Write a class in Kotlin and call it in Java
Using the database (SQL Server 2014) from a Java program 2018/01/04
Find a subset in Java
Null-safe program in Java (Eclipse)
Measured parallel processing in Java
[Beginner] I made a program to sell cakes in Java
Implement Java Interface in JRuby class and call it from Java
Easily get an integer from a system property in Java
Get a non-empty collection from an Optional stream in java
Call Chain from Chain in Spring Integration
Call Kotlin's sealed class from Java
3 Implement a simple interpreter in Java
I created a PDF in Java.
Date processing in Java (LocalDate: Initialization)
[Note] What I learned in half a year from inexperienced (Java)
[Note] What I learned in half a year from inexperienced (Java) (1)
Run node.js from android java (processing)
Access Teradata from a Java application
A simple sample callback in Java
Create a Servlet program in Eclipse
[Note] What I learned in half a year from inexperienced (Java) (3)
Make a SOAP call in C #
About file copy processing in Java
Get stuck in a Java primer
Call TensorFlow Java API from Scala
Order of processing in the program
Call the super method in Java
Access MySQL on a Docker container from a local (host OS) Java program
A story about a Spring Boot project written in Java that supports Kotlin
Sample program that returns the hash value of a file in Java
When calling println etc. from an external Java class file in Processing
About returning a reference in a Java Getter
Study Deep Learning from scratch in Java.
What is a class in Java language (3 /?)
Data processing using stream API from Java 8
Call GitHub API from Java Socket API part2
OCR in Java (character recognition from images)
Call the Windows Notification API in Java
Reverse Key from Value in Java Map
Using JavaScript from Java in Rhino 2021 version
A program that calculates factorials from 2 to 100
How to call Swift 5.3 code from Objective-C
Java creates a pie chart in Excel
What is a class in Java language (1 /?)
What is a class in Java language (2 /?)
Try running a Kubernetes Job from Java
Why does Java call a file a class?
Create a TODO app in Java 7 Create Header
A Java engineer compared Swift, Kotlin, and Java.
Try making a calculator app in Java
Call Java methods from Nim using jnim