Use JAR file in c++/c

13,917

You need to use the Java Invocation API, described here. This example code (from that link) shows how to load in a Java Virtual Machine and use it to call a static Java method named test with an int argument, located in the class Main. In this example, the path to the JAR file would be set using the vm_args.classpath variable.

#include <jni.h>       /* where everything is defined */
...
JavaVM *jvm;       /* denotes a Java VM */
JNIEnv *env;       /* pointer to native method interface */
JDK1_1InitArgs vm_args; /* JDK 1.1 VM initialization arguments */
vm_args.version = 0x00010001; /* New in 1.1.2: VM version */
/* Get the default initialization arguments and set the class 
 * path */
JNI_GetDefaultJavaVMInitArgs(&vm_args);
vm_args.classpath = ...;
/* load and initialize a Java VM, return a JNI interface 
 * pointer in env */
JNI_CreateJavaVM(&jvm, &env, &vm_args);
/* invoke the Main.test method using the JNI */
jclass cls = env->FindClass("Main");
jmethodID mid = env->GetStaticMethodID(cls, "test", "(I)V");
env->CallStaticVoidMethod(cls, mid, 100);
/* We are done. */
jvm->DestroyJavaVM();

If you wanted to call a non-static method, the code would be only slightly different, and the rest of the Java Native Interface tutorial explains all you need to know.

Share:
13,917

Related videos on Youtube

sachin
Author by

sachin

-(id) init{ self = [ios init] + [flex init] + [cakephp init]; return self; }

Updated on June 04, 2022

Comments

  • sachin
    sachin almost 2 years

    Possible Duplicate:
    How to access the Java method in a C++ application

    I need to use JAR file in c++ program. i.e. from c++ i need to call java function, for example, In java there is a function who accept 2 integer and return addition of that, Now i need to call this function from c++. Please guide me Thanks in advance.

  • sachin
    sachin over 12 years
    HI, here we are using java class, but i need to include jar file
  • Ernest Friedman-Hill
    Ernest Friedman-Hill over 12 years
    As I said, set the vm_args.classpath variable to the path to the jar file -- i.e., "./libs/thejarfile.jar". The JVM will find the class inside the jar file. If you need to include more than one jar file, then this same variable should be a colon (UNIX) or semicolon (WINDOW) -separated list of jar file paths.