changeset 4:b04bfca58e58

First attempt at wrapping tools using a C program and the JNI library.
author Andrew John Hughes <gnu_andrew@member.fsf.org>
date Thu, 29 Nov 2007 16:46:44 +0000
parents dbc17dd9fa08
children 23c4c196778a
files ChangeLog tools/library.c
diffstat 2 files changed, 97 insertions(+), 0 deletions(-) [+]
line wrap: on
line diff
--- a/ChangeLog	Thu Nov 29 13:48:56 2007 +0000
+++ b/ChangeLog	Thu Nov 29 16:46:44 2007 +0000
@@ -1,3 +1,9 @@
+2007-11-29  Andrew John Hughes  <gnu_andrew@member.fsf.org>
+
+	* tools/library.c:
+	Initial attempt to wrap tools using a C program and
+	the JNI library.
+
 2007-11-29  Andrew John Hughes  <gnu_andrew@member.fsf.org>
 
 	* Makefile.am:
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/tools/library.c	Thu Nov 29 16:46:44 2007 +0000
@@ -0,0 +1,91 @@
+#include <jni.h>
+#include <string.h>
+#include <stdlib.h>
+
+int main(int argc, char** argv)
+{
+  JNIEnv *env;
+  JavaVM *vm;
+  JavaVMInitArgs vm_args;
+  JavaVMOption options[argc-1];
+  char** read_pos;
+  char** write_pos;
+  int a;
+  jint vm_count;
+  jint main_count;
+  jint res;
+  jclass cls;
+  jmethodID main_method;
+  jclass string_class;
+  jobjectArray args;
+
+  vm_args.version = JNI_VERSION_1_2;
+  vm_args.ignoreUnrecognized = JNI_TRUE;
+  read_pos = argv + 1;
+  write_pos = argv;
+  for (a = 0; a < argc - 1; ++a)
+    {
+      if (strncmp(*read_pos, "-J", (size_t)2) == 0)
+	{
+	  options[vm_count].optionString = *read_pos + 2;
+	  ++vm_count;
+	}
+      else
+	{
+	  *write_pos = *read_pos;
+	  ++write_pos;
+	  ++main_count;
+	}
+      ++read_pos;
+    }
+  for (a = 0; a < main_count; ++a)
+    printf("main option %d: %s\n", a, argv[a]);
+  for (a = 0; a < vm_count; ++a)
+    printf("vm option %d: %s\n", a, options[a].optionString);
+  vm_args.options = options;
+  vm_args.nOptions = vm_count;
+
+  res = JNI_CreateJavaVM(&vm, (void**)&env, &vm_args);
+  if (res < 0)
+    {
+      fprintf(stderr, "Couldn't create Java VM\n");
+      exit(-1);
+    }
+  cls = (*env)->FindClass(env, "CLASS_NAME");
+  if (cls == NULL) {
+    goto destroy;
+  }
+ 
+  main_method = (*env)->GetStaticMethodID(env, cls, "main",
+					  "([Ljava/lang/String;)V");
+  if (main_method == NULL) {
+    goto destroy;
+  }
+
+  string_class = (*env)->FindClass(env, "java/lang/String");
+  args = (*env)->NewObjectArray(env, main_count, string_class, NULL);
+  if (args == NULL) {
+    goto destroy;
+  }
+
+  for (a = 0; a < main_count; ++a)
+    {
+      jstring jstr;
+
+      jstr = (*env)->NewStringUTF(env, *argv);
+      if (jstr == NULL) 
+	goto destroy;
+      ++argv;
+      (*env)->SetObjectArrayElement(env, args, a, jstr);
+    }
+
+  (*env)->CallStaticVoidMethod(env, cls, main_method, args);
+ 
+ destroy:
+  if ((*env)->ExceptionOccurred(env)) 
+    (*env)->ExceptionDescribe(env);
+  (*vm)->DestroyJavaVM(vm);
+  
+  return 0;
+}
+