igoutas
igoutas

Reputation: 145

Call multiple time JNI in single Tread

I need to call some methods from a jar using JNI in c++.But i need to call it a lot of times in different instances of thesame class. My JNI is something like this

JavaVM *jvm;       /* denotes a Java VM */
JNIEnv *env;       /* pointer to native method interface */
JavaVMInitArgs vm_args; /* JDK/JRE 6 VM initialization arguments */
jmethodID Sim_constr = NULL;
jmethodID Read_XML = NULL;
jmethodID configure = NULL;
jmethodID initial = NULL;
jmethodID results = NULL;
jint step = 60;
JavaVMOption* options = new JavaVMOption[1];
options[0].optionString = "-Djava.class.path=<My jar>";
vm_args.version = JNI_VERSION_1_8;
vm_args.nOptions = 1;
vm_args.options = options;
vm_args.ignoreUnrecognized = JNI_TRUE;
/* load and initialize a Java VM, return a JNI interface
 * pointer in env */`

long status = JNI_CreateJavaVM(&jvm, (void**)&env, &vm_args);
if (status == JNI_ERR){
    exit(10);
}
//Some Java method Calls... `

I need to set once the JNI and then just call 3-4 methods OR to kill/delete completely the JNI parameters and then create it again.

Upvotes: 0

Views: 1065

Answers (1)

suryakrish
suryakrish

Reputation: 132

I suppose you may try to accomplish the following

After creating a JVM using CreateJavaVM method your JVM remains Global for all instance of the class, the environment variable(env) should be local for each instance of the class. And also env var for each instance must be used to call your methods many times using different instances.

This snippet will get you the env from JVM:(place this such that every instance has local copy of env and global copy of jvm)

After creating the instance you have to attach these env to the current thread(i.e current instance)

JNIEnv * g_env;
 int getEnvStat = jvm->GetEnv((void **)&g_env, JNI_VERSION_1_8);

 if (getEnvStat == JNI_EDETACHED) {
  printf("GetEnv: not attached");
  getEnvStat = g_vm->AttachCurrentThread((void **) &g_env, NULL);
  if ( getEnvStat != 0) {
   printf("Failed to attach");
  }
 } else if (getEnvStat == JNI_OK) {
 } else if (getEnvStat == JNI_EVERSION) {
  printf("GetEnv: version not supported");
 }
//use the g_env variable for java method calls
//Rememeber to use this code as a local copy for each instance

Upvotes: 1

Related Questions