2012-01-24 34 views
8

Tôi biết rằng mã Java có thể gọi mã C++ thông qua JNI. Có thể, tuy nhiên, để gọi mã Java từ C++ một lần nữa thông qua JNI hoặc với bất kỳ phương pháp nào khác?C++ có thể gọi mã Java không?

+14

Tôi không biết cụ Dumbledore thích lập trình :) –

+4

tôi nghe ông là một thuật sĩ tại những thứ! – Luminously

+10

@Tôi đã nhìn thấy mã của anh ấy. Thật kỳ diệu. – mcfinnigan

Trả lời

10

Bạn chắc chắn có thể. Dưới đây là một ví dụ:

Dưới đây là file 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(); 
     } 
    } 
} 

Và heres một số C++ sử dụng nó:

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

Hoàn hảo, cảm ơn :-) –

4

Bạn cũng có thể sử dụng SWIG để tự động tạo các tập tin JNI. Quá trình cài đặt có thể là một chút khó khăn nhưng nó rất hữu ích khi bạn có rất nhiều mã C++ để lộ

http://www.swig.org/index.php

Các vấn đề liên quan