使用JNI从java到c ++调用非静态方法

时间:2014-06-03 05:20:22

标签: java java-native-interface jnienv

我试图使用JNI将非静态方法从java调用到C ++ 我的Java代码在这里:

public class hellojava
{
  public static void main(String args[]) 
  {
     System.out.println("Hello World!");
     System.out.println("This is the main function from the HelloWorld java class.");
  }

public void message()
{
    System.out.println("call from object");

}

}

我的C ++代码在这里:

#include <stdio.h>
#include <jni.h>


JNIEnv* create_vm(JavaVM ** jvm) {

JNIEnv *env;
JavaVMInitArgs vm_args;
JavaVMOption options;

options.optionString = "-Djava.class.path=/home/../nonstaticJavaMethods/";     
//Path to the java source code

vm_args.version = JNI_VERSION_1_6; //JDK version. This indicates version 1.6
vm_args.nOptions = 1;
vm_args.options = &options;
vm_args.ignoreUnrecognized = 0;


int ret = JNI_CreateJavaVM(jvm, (void**)&env, &vm_args);
if(ret < 0)
    printf("\nUnable to Launch JVM\n");     
return env;
}

int main(int argc, char* argv[])
{
JNIEnv *env;
JavaVM * jvm;
env = create_vm(&jvm);
if (env == NULL)
    return 1;   


//jclass clsH=NULL;
jmethodID midMain = NULL;
jstring square;
jclass clsH = env->FindClass("helloWorld");
jmethodID constructor = env->GetMethodID(clsH, "<init>", "void(V)");
jobject object = env->NewObject(clsH, constructor);



//Obtaining Method IDs
if (clsH != NULL)
{          midMain = env->GetMethodID(clsH, "message", "void(V)");
           env->CallVoidMethod(clsH, midMain, object,NULL); 
}
else
{
    printf("\nUnable to find the requested class\n");       
}




//Release resources.
int n = jvm->DestroyJavaVM();
return 0;

}

My code compiles but it is giving me runtime error. Following is the error

Java Runtime Environment检测到致命错误:

 SIGSEGV (0xb) at pc=0x00007fdf3f5126bb, pid=11302, tid=140596827092800

JRE version: OpenJDK Runtime Environment (7.0_55-b14) (build 1.7.0_55-b14)
Java VM: OpenJDK 64-Bit Server VM (24.51-b03 mixed mode linux-amd64 compressed oops)
Problematic frame:
V  [libjvm.so+0x5c46bb]  alloc_object(_jclass*, Thread*)+0x1b

 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  

 /home/../nonstaticJavaMethods/hs_err_pid11302.log      
 Aborted!

2 个答案:

答案 0 :(得分:2)

除了immibis'回答之外,我还认为电话

jclass clsH = env->FindClass("helloWorld");

没有返回任何内容,因为您的类被称为

public class hellojava

因此,您的应用程序可能是GetMethodID()NewObject()

中的分段错误

答案 1 :(得分:1)

void(V)不是有效的方法描述符。

因为没有名为<init>的方法带有描述符void(V)(因为它无效),所以GetMethodID会返回0。您尝试使用此无效方法ID创建新对象。

不带参数且返回void(构造函数是)的方法的方法描述符是()V