簡體   English   中英

使用JNI從Java到cpp調用非靜態方法

[英]call nonstatic methods from java to cpp using JNI

我正在嘗試使用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運行時環境檢測到致命錯誤:

 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!

除了immibis的回答,我也認為電話

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

沒有返回任何東西,因為您的班級被稱為

public class hellojava

因此,您的應用程序可能在GetMethodID()NewObject()段錯誤

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

因為沒有帶有描述符void(V)稱為<init>方法(之所以無效,因為它無效,所以沒有),所以GetMethodID返回0。然后,您嘗試使用此無效的方法ID創建一個新對象。

不帶任何參數並返回void (構造函數是)的方法的方法描述符是()V

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM