2012-01-24 52 views
8

我知道Java代碼可以通過JNI調用C++代碼。但是,是否可以通過JNI或使用其他方法再次從C++調用Java代碼?C++可以調用Java代碼嗎?

+14

我不知道鄧布利多喜歡編程:) –

+4

我聽到他在東西向導! – Luminously

+10

@我很高興見過他的代碼。它很神奇。 – mcfinnigan

回答

10

是的,你當然可以。這裏有一個例子:

這裏的java文件:

public class InvocationHelloWorld { 
    public static void main(String[] args) { 
     System.out.println("Hello, World!"); 
     System.out.println("Arguments sent to this program:"); 
     if (args.length == 0) { 
      System.out.println("(None)"); 
     } else { 
      for (int i=0; i<args.length; i++) { 
       System.out.print(args[i] + " "); 
      } 
      System.out.println(); 
     } 
    } 
} 

而且繼承人一些C++使用它:

void invoke_class(JNIEnv* env) { 
    jclass helloWorldClass; 
    jmethodID mainMethod; 
    jobjectArray applicationArgs; 
    jstring applicationArg0; 

    helloWorldClass = (env)->FindClass("InvocationHelloWorld"); 
    if(! helloWorldClass) 
    { 
    std::cerr<<"Couldn't get \"InvocationHelloWorld\""<<std::endl; 
    return; 
    } 

    mainMethod = (env)->GetStaticMethodID(helloWorldClass, "main", "([Ljava/lang/String;)V"); 
    if(! mainMethod) 
    { 
    std::cerr<<"Coulnd't get \"InvocationHelloWorld::main\""<<std::endl; 
    return; 
    } 

    applicationArgs = (env)->NewObjectArray(1, (env)->FindClass("java/lang/String"), NULL); 
    applicationArg0 = (env)->NewStringUTF("From-C-program"); 
    (env)->SetObjectArrayElement(applicationArgs, 0, applicationArg0); 

    (env)->CallStaticVoidMethod(helloWorldClass, mainMethod, applicationArgs); 
} 
+0

完美,謝謝:-) –

相關問題