The Haskell standard includes a native foreign function interface
(FFI). Using it can be a bit involved and only C support is
implemented in GHC. inline-java lets you call any JVM function
directly, from Haskell, without the need to write your own foreign
import declarations using the FFI. In the style of inline-c for
C and inline-r for calling R, inline-java lets you name any
function to call inline in your code. It is implemented on top of the
jni and jvm packages using a GHC Core plugin
to orchestrate compilation and loading of the inlined Java snippets.
Example
Graphical Hello World using Java Swing:
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE OverloadedStrings #-}
moduleMainwhereimportData.Text (Text)
importLanguage.JavaimportLanguage.Java.Inlinemain::IO()
main = withJVM []$do
message <- reflect ("Hello World!"::Text)
[java| {
javax.swing.JOptionPane.showMessageDialog(null, $message);
} |]
If -ddump-to-file is in effect, the java code is dumped to
<module>.dump-java instead.
Troubleshooting
Build-time error package or class Blah does not exist
inline-java is going to invoke the javac compiler, and any classes
used in java quotations need to be reachable via the CLASSPATH
environment variable. For instance,
Haskell threads need to be attached to the JVM before making JNI calls.
Foreign.JNI.withJVM attaches the calling thread, and other threads
can be attached with Foreign.JNI.runInAttachedThread. When the JVM
calls into Haskell, the thread is already attached.
Run-time error ThreadNotBound
JNI calls need to be done from bound threads. The thread invoking the
main function of a program is bound. Threads created with forkOS
are bound. In other threads, Control.Concurrent.runInBoundThread
can be used to run a computation in a bound thread.
Run-time error java.lang.NoClassDefFoundError
Classes might not be found at runtime if they are not in a folder or
jar listed in the parameter -Djava.class.path=<classpath> passed
to withJVM.
Additionally, classes might not be found if a thread other than the one
calling main is trying to use them. One solution is to have the thread
calling main load all the classes in advance. Then the classes will
be available in the JVM for other threads that need them.
Calling Language.Java.Inline.loadJavaWrappers will have the effect of
loading all classes needed for java quotations, which will suffice in
many cases.
Another option is to set the context class loader of other threads,
so they earn the ability to load classes on their own. This might
work when the thread was attached to the JVM via the JNI, and
the context class loader is just null.
Any java exception that goes from Java to Haskell will be wrapped
as a value of type JVMException with a reference to the Java object
representing the exception. The message and the stack trace of the
exception can be retrieved from the exception object with more JNI
calls, e.g.
请发表评论