简体   繁体   English

从Java调用c ++,然后从相同的c ++方法调用Java方法

[英]Call from Java to c++ and then from the same c++ method make a call to java method

The following code can invoke a C++ method from Java. 以下代码可以从Java调用C ++方法。

JNITest.java JNITest.java

public class JNITest  {
    static {
        System.load("D:\\gagan docs\\TestJava\\Example.dll");
    }

    public native int intMethod(int n);

    public static void main(String[] args) {
        JNITest jnitest = new JNITest();
        int square=jnitest.intMethod(5);
        System.out.println("HelloWorld");
        System.out.println("From init method"+square);
    }

}

Example.cpp 范例.cpp

#include "JNITest.h"
#include<string.h>
JNIEXPORT jint JNICALL Java_JNITest_intMethod(JNIEnv *env, jobject obj, jint num)
{
    return num*num;
}

But when I try to call a java method from the above CPP using the following, the JVM crashes. 但是,当我尝试使用以下方法从上述CPP调用Java方法时,JVM崩溃。

I have also tried with createJavaVM method to create JVM, but it crashed. 我也尝试用createJavaVM方法创建JVM,但是它崩溃了。

Example.cpp 范例.cpp

#include "JNITest.h"
#include<string.h>
static JavaVM *jvm = NULL
JNIEXPORT jint JNICALL Java_JNITest_intMethod(JNIEnv *env, jobject obj, jint num) 
{
    JNIEnv* jenv;
    int res = jvm->AttachCurrentThread((void **)&jenv, NULL);
    return num*num;
}

I am using Linux(64 bit)machine and JDK 64 bit(Java 1.6). 我正在使用Linux(64位)计算机和JDK 64位(Java 1.6)。

I want to make a complete flow from Java -> C++ -> Java. 我想从Java-> C ++-> Java取得完整的流程。 Any information on this issue will be very useful. 关于此问题的任何信息将非常有用。

Calling Java from C++ is a (relatively) simple matter of: 从C ++调用Java是(相对)简单的事情:

JNIEXPORT jint JNICALL Java_JNITest_intMethod(JNIEnv *env, jobject obj, jint num)
{
    jint x = (env)->CallIntMethod(obj, method_id);
    // or, (env)->CallVoidMethod(obj, voidMethod, ...), etc.
}

This assumes the class of your jobject has the method identified by jmethodID . 假设您的jobject的类具有jmethodID标识的方法。 Obtaining the jmethodID is simple too: 获取jmethodID也很简单:

jclass class_inst = (env)->FindClass("pkg/to/my/stuff/Class");
jmethodID method_id = (env)->GetMethodId(class_inst, "methodName", "()I");

Getting the method you want to call for a particular class is probably your most challenging task, but not at all hard once you have a good grasp of fundamentals. 获得要为特定类调用的方法可能是您最具挑战性的任务,但是一旦您掌握了基本知识,就不会很难。

For a nice example (disclaimer: I'm the example's author), see inotify-interface.cpp . 有关一个很好的示例(免责声明:我是示例的作者),请参见inotify-interface.cpp

Note also, you probably aren't interested in calling AttachCurrentThread ! 另请注意,您可能对调用AttachCurrentThread 并不感兴趣!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM