6

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.

Community
  • 1
  • 1
sachin
  • 1,015
  • 4
  • 11
  • 24

1 Answers1

13

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.

Ernest Friedman-Hill
  • 80,601
  • 10
  • 150
  • 186
  • HI, here we are using java class, but i need to include jar file – sachin Jan 13 '12 at 12:12
  • 1
    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. – Ernest Friedman-Hill Jan 13 '12 at 12:13