Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use JAR file in c++/c [duplicate]

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.

like image 295
sachin Avatar asked Jan 13 '12 11:01

sachin


1 Answers

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.

like image 143
Ernest Friedman-Hill Avatar answered Oct 16 '22 05:10

Ernest Friedman-Hill