Java native 接口(interface) - C++ 不等待 java 函数完成

标签 java c++ java-native-interface stanford-nlp

我希望用 java 编写的 Stanford Core NLP 的功能可以在 C++ 中使用。为此,我使用了 Java native 接口(interface)。我有一个 Java 对象,它以一种更容易从 C++ 调用的方式包装了多个函数。但是,当我确实调用这些函数时,C++ 不会等待函数完成后再转到下一个函数。

Java 对象有一个我用于测试的 Main 函数,它调用所有适当的函数来进行测试。当只运行 Java 时,它工作得很好。注解等待设置完成(这确实需要一段时间),获取依赖项的函数等待注解函数完成。完全预期和正确的行为。 当我开始从 C++ 调用 java 函数时,问题就来了。部分 java 函数将运行,但它会在某些点退出并返回到 C++,如下所述。我希望 C++ 等待 java 方法完成。

如果重要的话,我使用的是 Stanford Core NLP 3.9.2。

我使用 NLP .jar 文件附带的 StanfordCoreNlpDemo.java 中的代码作为起点。

import java.io.*;
import java.util.*;

// Stanford Core NLP imports

public class StanfordCoreNLPInterface {

    Annotation annotation;
    StanfordCoreNLP pipeline;

    public StanfordCoreNLPInterface() {}

    /** setup the NLP pipeline */
    public void setup() {
        // Add in sentiment
        System.out.println("creating properties");
        Properties props = new Properties();
        props.setProperty("annotators", "tokenize, ssplit, pos, lemma, ner, parse, dcoref, sentiment");
        System.out.println("starting the parser pipeline");
        //<---- doesn't get past this point
        pipeline = new StanfordCoreNLP(props);
        System.out.println("started the parser pipeline");
    }

    /** annotate the text */
    public void annotateText(String text) {
        // Initialize an Annotation with some text to be annotated. The text is the argument to the constructor.
        System.out.println("text");
        System.out.println(text);
        //<---- doesn't get past this point
        annotation = new Annotation(text);
        System.out.println("annotation set");
        // run all the selected annotators on this text
        pipeline.annotate(annotation);
        System.out.println("annotated");
    }

    /** print the dependencies */
    public void dependencies() {
        // An Annotation is a Map with Class keys for the linguistic analysis types.
        // You can get and use the various analyses individually.
        // For instance, this gets the parse tree of the first sentence in the text.
        List<CoreMap> sentences = annotation.get(CoreAnnotations.SentencesAnnotation.class);
        if (sentences != null && ! sentences.isEmpty()) {
            CoreMap sentence = sentences.get(0);
            System.out.println("The first sentence dependencies are:");
            SemanticGraph graph = sentence.get(SemanticGraphCoreAnnotations.EnhancedPlusPlusDependenciesAnnotation.class);
            System.out.println(graph.toString(SemanticGraph.OutputFormat.LIST));
        }
    }

    /** Compile: javac -classpath stanford-corenlp-3.9.2.jar -Xlint:deprecation StanfordCoreNLPInterface.java*/
    /** Usage: java -cp .:"*" StanfordCoreNLPInterface*/
    public static void main(String[] args) throws IOException {
        System.out.println("starting main function");
        StanfordCoreNLPInterface NLPInterface = new StanfordCoreNLPInterface();
        System.out.println("new object");
        NLPInterface.setup();
        System.out.println("setup done");

        NLPInterface.annotateText("Here is some text to annotate");
        NLPInterface.dependencies();
    }
}

我使用了本教程中的代码 http://tlab.hatenablog.com/entry/2013/01/12/125702 作为起点。

#include <jni.h>

#include <cassert>
#include <iostream>


/** Build:  g++ -Wall main.cpp -I/usr/lib/jvm/java-8-openjdk/include -I/usr/lib/jvm/java-8-openjdk/include/linux -L${LIBPATH} -ljvm*/
int main(int argc, char** argv) {
    // Establish the JVM variables
    const int kNumOptions = 3;
    JavaVMOption options[kNumOptions] = {
        { const_cast<char*>("-Xmx128m"), NULL },
        { const_cast<char*>("-verbose:gc"), NULL },
        { const_cast<char*>("-Djava.class.path=stanford-corenlp"), NULL },
        { const_cast<char*>("-cp stanford-corenlp/.:stanford-corenlp/*"), NULL }
    };

    // JVM setup before this point.
    // java object is created using env->AllocObject();
    // get the class methods
    jmethodID mid =
        env->GetStaticMethodID(cls, kMethodName, "([Ljava/lang/String;)V");
    jmethodID midSetup =
        env->GetMethodID(cls, kMethodNameSetup, "()V");
    jmethodID midAnnotate =
        env->GetMethodID(cls, kMethodNameAnnotate, "(Ljava/lang/String;)V");
    jmethodID midDependencies =
        env->GetMethodID(cls, kMethodNameDependencies, "()V");
    if (mid == NULL) {
        std::cerr << "FAILED: GetStaticMethodID" << std::endl;
        return -1;
    }
    if (midSetup == NULL) {
        std::cerr << "FAILED: GetStaticMethodID Setup" << std::endl;
        return -1;
    }
    if (midAnnotate == NULL) {
        std::cerr << "FAILED: GetStaticMethodID Annotate" << std::endl;
        return -1;
    }
    if (midDependencies == NULL) {
        std::cerr << "FAILED: GetStaticMethodID Dependencies" << std::endl;
        return -1;
    }
    std::cout << "Got all the methods" << std::endl;

    const jsize kNumArgs = 1;
    jclass string_cls = env->FindClass("java/lang/String");
    jobject initial_element = NULL;
    jobjectArray method_args = env->NewObjectArray(kNumArgs, string_cls, initial_element);

    // prepare the arguments
    jstring method_args_0 = env->NewStringUTF("Get the flask in the room.");
    env->SetObjectArrayElement(method_args, 0, method_args_0);
    std::cout << "Finished preparations" << std::endl;

    // run the function
    //env->CallStaticVoidMethod(cls, mid, method_args);
    //std::cout << "main" << std::endl;
    env->CallVoidMethod(jobj, midSetup);
    std::cout << "setup" << std::endl;
    env->CallVoidMethod(jobj, midAnnotate, method_args_0);
    std::cout << "annotate" << std::endl;
    env->CallVoidMethod(jobj, midDependencies);
    std::cout << "dependencies" << std::endl;
    jvm->DestroyJavaVM();
    std::cout << "destroyed JVM" << std::endl;

    return 0;
}

用 g++ 和 -Wall 编译 C++ 不会给出警告或错误,用 javac 编译 Java 也不会。当我运行 C++ 代码时,我得到以下输出。

Got all the methods
Finished preparations
creating properties
starting the parser pipeline
setup
text
Get the flask in the room.
annotate
dependencies
destroyed JVM

在启动 C++ 的 couts 和 printlines 之后,您可以看到 C++ 如何能够在调用 java 中的设置方法之前成功获取方法并完成 JVM 和方法准备。该设置方法启动并调用第一个打印行,创建属性并分配值,然后在它可以启动解析器管道并返回到 C++ 之前退出。 它基本上是相同的故事向前发展,注释文本函数被调用并成功地从 C++ 方法调用接收文本,但在创建注释对象之前退出。我在依赖项中没有那么多调试 printlns,因为那时它并不重要,但不用说,现有的 printlns 都没有被调用。 最后,JVM 被销毁,程序结束。

感谢您提供的任何帮助或见解。

最佳答案

JNI 方法调用始终是同步的。当它们在到达方法末尾之前返回时,那是因为代码遇到了异常。这不会自动传播到 C++ 异常。您始终必须在每次调用后检查异常情况。

代码在从其他 Java 代码调用时运行良好但在使用 JNI 调用时运行良好的代码的一个常见问题是 VM 的类路径。虽然 java.exe 将解析 * 并将每个匹配的 JAR 添加到类路径,但使用调用接口(interface)的程序必须自己执行此操作。 JavaVMOption 中的 -Djava.class.path 仅适用于真实文件。此外,您只能使用实际的 VM 选项,而不能使用 -cp 之类的参数,因为它们也只能由 java.exe 解析,而不是调用接口(interface)的一部分。

关于Java native 接口(interface) - C++ 不等待 java 函数完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56729163/

相关文章:

java - 如何在 Struts 2 上使用 Spring Security 3?

java - 使用构造函数查找孪生素数

c++ - 模板链接器错误的显式实例化

c++ - 意外异常

android - OpenCV 和 C++ : "Can' t resolve variable 'Mat` "

java - Tomcat DLL 已加载到另一个类加载器中

java - 通过 ProcessBuilder 调用脚本和直接通过 JNI 调用 api 哪个更好?

java - 如何使用 getPurchases() - Android

java - Java 中的图像处理

c++ - 重载 = 运算符悖论