You aren't checking any error returns from the JNI functions. You need to check for errors.
Core dump following g++ compilation + link with jni and subsequent execution of application using C++ and Java
-
13-12-2021 - |
Pergunta
I require to execute some arbitrary Java code from within C++. I am utilizing the JNI for this but have encountered an issue. The C++ file compiles fine, however upon execution the following is produced:
A fatal error has been detected by the Java Runtime Environment:
SIGSEGV (0xb) at pc=0xb6f90ffb, pid=10063, tid=3062122240
JRE version: 7.0_10-b18 Java VM: Java HotSpot(TM) Server VM (23.6-b04 mixed mode linux-x86 ) Problematic frame: V [libjvm.so+0x440ffb] JNI_ArgumentPusherVaArg::JNI_ArgumentPusherVaArg(_jmethodID*, char*)+0x1b
Core dump written. Default location: /home/alex/candjava/core or core.10063
An error report file with more information is saved as: /home/alex/candjava/hs_err_pid10063.log
If you would like to submit a bug report, please visit: http://bugreport.sun.com/bugreport/crash.jsp
Aborted (core dumped)
The compilation command:
g++ sample.cpp -o app -I $JAVA_HOME/include -I $JAVA_HOME/include/linux -I $JAVA_HOME/jre/lib/i386/client -L$JAVA_HOME/jre/lib/i386/client -ljvm -Wno-write-strings
where $JAVA_HOME
is /usr/lib/jvm/java-7-oracle
The java source:
public class Main{
public void test(){
System.out.println("HELLO WORLD");
}
}
The C++ source:
#include <stdio.h>
#include <stdlib.h>
#include <jni.h>
#include <string.h>
int main()
{
JavaVM *jvm; /* denotes a Java VM */
JNIEnv *env; /* pointer to native method interface */
JavaVMInitArgs vm_args; /* JDK/JRE 6 VM initialization arguments */
JavaVMOption* options = new JavaVMOption[1];
options[0].optionString = "-D java.class.path=/usr/lib/jvm/java-7-oracle/bin";
vm_args.version = JNI_VERSION_1_6;
vm_args.nOptions = 1;
vm_args.options = options;
vm_args.ignoreUnrecognized = false;
/* load and initialize a Java VM, return a JNI interface
* pointer in env */
JNI_CreateJavaVM(&jvm, (void**)&env, &vm_args);
delete options;
/* 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();
}
Any help with this would be much appreciated!
Solução
Outras dicas
jmethodID mid = env->GetStaticMethodID(cls, "test", "(I)V");
says your function is void and you have integer as argument. but you are not sending any integer argument it must be as follows
jmethodID mid = env->GetStaticMethodID(cls, "test", "()V");
there are some obvious errors in your source code.
- the test method in the Main class should be static
- the test parameter should be int
- the java.class.path parameter is ridiculous
I also have the third problem. change the option -Djava.class.path=/Path-to-your-class-file-directory
will be ok. (Mine is "-Djava.class.path=."
)