# JNI pour créer une JFrame



## oimy (11 Juin 2018)

Bonjour,

Mon but est de créer une Frame en utilisant JNI. Cela fonctionne quand j'utilise un code simple et que je le compile tout seul. Par contre cela ne fonctionne pas quand je l'intègre à mon projet global.


La fonction RunCocoaMain() me permet de faire fonctionner la JFrame comme expliqué dans ce forum (https://stackoverflow.com/questions/14661249/java-jni-creating-a-swing-window-using-jni-from-c). Cela fonctionne parfaitement tout seul par contre lorsque j'insère le code dans mon projet global, j'ai une erreur pendant l'exécution dans la fonction RunCocoaMain() au niveau de la ligne "id _Nullable app = objc_msgSend(clazz, sel_registerName("sharedApplication"));"

Erreur :
A fatal error has been detected by the Java Runtime Environment:
SIGSEGV (0xb) at pc=0x00007fff5f159165, pid=4917, tid=0x0000000000000307
JRE version: Java(TM) SE Runtime Environment (8.0_172-b11) (build 1.8.0_172-b11)
Java VM: Java HotSpot(TM) 64-Bit Server VM (25.172-b11 mixed mode bsd-amd64 compressed oops)
Problematic frame:
C  [SkyLight+0x20a165]  _ZN12_GLOBAL__N_112get_registryEv.8847+0x33
Failed to write core dump. Core dumps have been disabled. To enable core dumping, try "ulimit -c unlimited" before starting Java again
An error report file with more information is saved as:
/Users/.../Desktop/projet/total_test/hs_err_pid4917.log
If you would like to submit a bug report, please visit:
http://bugreport.java.com/bugreport/crash.jsp
The crash happened outside the Java Virtual Machine in native code.
See problematic frame for where to report the bug.

Mes questions sont les suivantes :
_ Etant novice dans l'interprétation du fichier .log, quelqu'un pourrai m'indiquer un auto ou alors me dire ce qu'il indique comme problème ?
_D'où vient le fait que le code fonctionne tout seul mais pas quand je l'insère dans mon projet global ?

PS : Le code est plus bas

Merci d'avance


----------



## oimy (11 Juin 2018)

le code simple cpp:

```
// Example 2 of JNI invocation. 
// The java environment is prepared.  Errors are reported. 
// Call to a simple static java methods 
// License: ZLIB license (see license.txt)
// (c) Copyright 2015 by cth027

#include <iostream>
#include <jni.h>
#include <objc/objc-runtime.h>

void runCocoaMain(void)
{
    id clazz = (id) objc_getClass("NSApplication");
    id _Nullable app = objc_msgSend(clazz, sel_registerName("sharedApplication"));
   
    objc_msgSend(app, sel_registerName("run"));
}


int main()
{
    using namespace std;
    JavaVM *jvm;                // Pointer to the JVM (Java Virtual Machine)
    JNIEnv *env;                // Pointer to native interface
    JavaVMInitArgs vm_args;                        // Initialization arguments
    JavaVMOption* options = new JavaVMOption[1];   // JVM invocation options
    options[0].optionString = "-Djava.class.path=.";   // where to find java .class
    vm_args.version = JNI_VERSION_1_8;             // minimum Java version
    vm_args.nOptions = 1;                          // number of options
    vm_args.options = options;
    vm_args.ignoreUnrecognized = JNI_TRUE;     // invalid options make the JVM init fail
    jint rc = JNI_CreateJavaVM(&jvm, (void**)&env, &vm_args);  // YES !!
    delete options;    // we then no longer need the initialisation options. 
if (rc == JNI_ERR) {
    printf("All done, bye bye!\n");
}
    if(rc != JNI_OK) {
        if(rc == JNI_EVERSION)
            cerr << "FATAL ERROR: JVM is oudated and doesn't meet requirements" << endl;
        else if(rc == JNI_ENOMEM)
            cerr << "FATAL ERROR: not enough memory for JVM" << endl;
        else if(rc == JNI_EINVAL)
            cerr << "FATAL ERROR: invalid ragument for launching JVM" << endl;
        else if(rc == JNI_EEXIST)
            cerr << "FATAL ERROR: the process can only launch one JVM an not more" << endl;
        else
            cerr << "FATAL ERROR:  could not create the JVM instance (error code " << rc << ")" << endl;
        cin.get();
        exit(EXIT_FAILURE);
    }

    cout << "JVM load succeeded. \nVersion ";
    jint ver = env->GetVersion();
    cout << ((ver >> 16) & 0x0f) << "." << (ver & 0x0f) << endl;
    jclass cls2 = env->FindClass("MyTest2");  // try to find the class 
    if(cls2 == nullptr) {
        cerr << "ERROR: class not found !";
    }
    else {                                  // if class found, continue
        cout << "Class MyTest found" << endl;
        jmethodID mid = env->GetStaticMethodID(cls2, "run", "()V");  // find method
        if(mid == nullptr)
            cerr << "ERROR: method void mymain() not found !" << endl;
        else {
            cout << "===Call to java==================" << endl; 
            env->CallStaticVoidMethod(cls2, mid);                      // call method
            runCocoaMain();
            cout << "===End of call to java==========="<<endl;
        }
    }
   jvm->DestroyJavaVM();
    cout << "Press any key...";
    cin.get();
}
```


----------



## oimy (11 Juin 2018)

Code Java :

```
// MyTest.java test class for JNI experimentation 
// example 2
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;

public class MyTest2 {
   
    public static class Starter implements Runnable {
        public void run() {
            System.out.println("Runnning on AWT Queue.");
           
            JFrame.setDefaultLookAndFeelDecorated(true);
            JFrame frame = new JFrame("That's a frame!");
            frame.setSize(400, 200);
            JLabel label = new JLabel("A Label");
            frame.getContentPane().add(label);
            frame.setLocationRelativeTo(null);
            //Termine le processus lorsqu'on clique sur la croix rouge
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            //frame.pack();
            frame.setVisible(true);
           
            //JButton button;
            //JPanel panel;
           
            // my error lines are under the "panel" and  "button"
            // it says i must implement the variables. what does that mean???
            //panel.add(button);
        }
    }
   
    public static class GUI implements Runnable {
        public void run() {
            try {
                System.out.println("Going to put something on the AWT queue.");
                SwingUtilities.invokeAndWait(new Starter());
                System.out.println("2.");
            } catch (Exception exc) {
                throw new RuntimeException(exc);
            }
        }
    }
   
    public static void run() {
        Thread gui = new Thread(new GUI());
        gui.start();
    }
}
```


----------

