Advertisement
nopcodex90

CS210 - HelloWorld JNI Main Source Code From PDF

Dec 2nd, 2020
1,169
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.79 KB | None | 0 0
  1. #include <iostream>
  2. #include <jni.h>
  3.  
  4. using namespace std;
  5.  
  6. int main() {
  7.     JavaVM         *jvm; // Pointer to the JVM (Java Virtual Machine)
  8.     JNIEnv         *env; // Pointer to native interface
  9.     //================== prepare loading of Java VM ============================
  10.     // Initialization arguments
  11.     JavaVMInitArgs vm_args;
  12.     JavaVMOption   *options = new JavaVMOption[1]; //JVM invocation options
  13.  
  14.     // where to find java.class
  15.     options[0].optionString    = (char *) "-Djava.class.path=U:/HelloJavaWorld/bin";
  16.     vm_args.version            = JNI_VERSION_1_6; // minimum Java version
  17.     vm_args.nOptions           = 1; // number of options
  18.     vm_args.options            = options;
  19.     vm_args.ignoreUnrecognized = false; // invalid options make the JVM init fail
  20.  
  21.     //=============== load and initialize Java VM and JNI interface =============
  22.     jint rc = JNI_CreateJavaVM(&jvm, (void **) &env, &vm_args); // YES !!
  23.     delete options; // we then no longer need the initialization options.
  24.     if (rc != JNI_OK) {
  25.         // TO DO: error processing...
  26.         cin.get();
  27.         exit(EXIT_FAILURE);
  28.     }
  29.     //=============== Display JVM version =======================================
  30.     cout << "JVM load succeeded: Version ";
  31.     jint ver = env->GetVersion();
  32.     cout << ((ver >> 16) & 0x0f) << "." << (ver & 0x0f) << endl;
  33.  
  34.     jclass cls2 = env->FindClass("HelloJavaWorld"); // try to find the class
  35.     if (cls2 == nullptr) {
  36.         cerr << "ERROR: class not found !";
  37.     } else { // if class found, continue
  38.         std::cout << "Class MyTest found" << endl;
  39.         jmethodID mid = env->GetStaticMethodID(cls2, "sayhi", "()V"); // find method
  40.         if (mid == nullptr) {
  41.             cerr << "ERROR: method not found !" << endl;
  42.         } else {
  43.             env->CallStaticVoidMethod(cls2, mid); // call method
  44.             cout << endl;
  45.         }
  46.  
  47.         jvm->DestroyJavaVM();
  48.         return 0;
  49.     }
  50. }
  51.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement