Using Haskell with Java
Ben Horsfall
ben.horsfall at gmail.com
Fri Jan 7 19:40:20 EST 2005
On Sat, 08 Jan 2005 00:59:10 +0100, Bjorn Bringert
<d00bring at dtek.chalmers.se> wrote:
> You could probably use the "foreign export" feature of the Haskell
> Foreign Function Interface [1] to make your Haskell function(s) callable
> from C, and then write a Java Native Interface [2] wrapper in C.
I have found it impossible to call Haskell functions from Java using
this approach, because Java needs foreign code to be compiled as a
shared library, and GHC, on Linux at least, can't do that as far as I
know.
On the other hand a similar approach works well if you want to call
Java methods from a Haskell program. I haven't tried it with Swing,
but I made it work with JDBC a while ago. Here's an example, calling
toString() on a Java Object:
In Haskell:
import Foreign
type JObject = StablePtr ()
foreign import ccall toString :: JObject -> IO JObject
and in C:
#include <jni.h>
jobject toString(jobject obj) {
jclass clazz = (*env)->GetObjectClass(env, obj);
jmethodID m = (*env)->GetMethodID(env, clazz, "toString",
"()Ljava/lang/String;");
return (*env)->CallObjectMethod(env, obj, m);
}
Of course, there's more work to do: you need to start a JVM from your
Haskell program; you need a Java Object in the first place; and if you
want to see the string in Haskell, you have to unmarshall it using JNI
and FFI, and so on ...
P.S. Perhaps this discussion should move to the FFI list or haskell-cafe.
More information about the Glasgow-haskell-users
mailing list