Monday, March 16, 2009

Calling from Java Code

It looks like a thing called jInvoke MAY be fantastic.
To review, I need to call my native DLL from java code. The old way of doing this was with a thing called Java Native Interface (JNI). Make no mistake, raw JNI sucks. Really, really, sucks.

Enter Java 1.5 and Annotations, to save the day. Some guys have come up with JInvoke, that seems to hide most of the ugliness of JNI. It is pretty opaque, but at least it's not pages of error prone crap that must be hand generated and maintained for every call. The hard part is type conversion. JInvoke cooks all the c++ signatures in a poorly documented way. So surprise surprise, lots of trial and error. Still, I got my "app" to launch from java, and I'm kind of amazed :)


Given a c++ declaration

MANDELBROTLIB_API int launch(int argc, char **argv)

Visual Studio creates a dll with

?launch@@YAHHPAPAD@Z = ?launch@@YAHHPAPAD@Z (int __cdecl launch(int,char * *))

This must be declared in JInvoke as
@NativeImport(library = "Mandelbrot.dll", function="?launch@@YAHHPAPAD@Z", charset = Charset.ANSI)
public static native int launch(int argc, int[] argvalues);

My first stab at faking int[] argvalues starting from an array of Java Strings is

String emptyArgs[] = new String[]{""};
int argVptr;
int[] jInvokeArgv;

argVptr = com.jinvoke.Util.stringToPtrAnsi(emptyArgs[0]);

jInvokeArgv = new int[]{argVptr};
launch(args.length,jInvokeArgv);

This does not crash anything, so it may be the right track at least.

No comments:

Post a Comment