通过返回字符串的 JNI 从 C++ 调用 java 函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4359453/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 16:27:59  来源:igfitidea点击:

Calling a java function from C++ via JNI that returns a string

javac++java-native-interface

提问by klaus johan

Possible Duplicate:
How to access the Java method in a C++ application

可能的重复:
如何在 C++ 应用程序中访问 Java 方法

Suppose I have a Java class like this :

假设我有一个这样的 Java 类:

class MyClass
{
  String value = "a string value";

  String getValue()
  {
    return value;
  }
}

I've been trying for hours to implement a JNI function that calls a Java function and returns a string. Could someone show me through a snippet how to call the "getValue" function from a C++ using JNI and obtain a jstring variable with the value of String variable from "MyClass.

我已经尝试了几个小时来实现一个调用 Java 函数并返回一个字符串的 JNI 函数。有人可以通过一个片段向我展示如何使用 JNI 从 C++ 调用“getValue”函数,并从“MyClass.getValue”中获取带有 String 变量值的 jstring 变量。

// C++

// C++

jobject result;

jMethodID method_getValue = m_env->GetMethodID(native_object,"getValue","()Ljava/lang/String;");

result = m_env->CallObjectMethod(native_object, method_getValue);

回答by Naytzyrhc

jMethodID method_getValue = m_env->GetMethodID(native_object,"getValue","()Ljava/lang/String;");

here, native_object is supposed to be the class definition object (jclass) of MyClass

这里,native_object 应该是 MyClass 的类定义对象(jclass)

jmethodID GetMethodID(JNIEnv *env, jclass clazz, const char *name, const char *sig);

whereas to here:

而到这里:

result = m_env->CallObjectMethod(native_object, method_getValue);

NativeType CallMethod(JNIEnv *env, jobject obj, jmethodID methodID, ...);

NativeType CallMethod(JNIEnv *env, jobject obj, jmethodID methodID, ...);

Your CallObjectMethod expects as first parameter an object from MyClass, no jclass. http://download.oracle.com/javase/1.4.2/docs/guide/jni/spec/functions.html

您的 CallObjectMethod 需要来自 MyClass 的对象作为第一个参数,而不是 jclass。 http://download.oracle.com/javase/1.4.2/docs/guide/jni/spec/functions.html

so either one of the calls is wrong here...

所以这里的任何一个电话都是错误的......

probably the getMethodID... you should definitely check for NULL there.

可能是 getMethodID ... 你绝对应该在那里检查 NULL。

cheers,

干杯,