繁体   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