繁体   English   中英

Java本机接口-C ++不等待Java函数完成

[英]Java Native Interface - C++ is not waiting for java function completion

我希望用Java编写的Stanford Core NLP的功能在C ++中可用。 为此,我正在使用Java本机接口。 我有一个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

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

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

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

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

暂无
暂无

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

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