【问题标题】:JNI jstring from class variable?来自类变量的JNI jstring?
【发布时间】:2015-07-14 22:26:11
【问题描述】:

我的 Java 类中有一个字符串变量:

public class myclass {
    protected final String file;
    myclass(String f) {
        file = f;
    }

    public native void processFiles();
    public static void main(String[] args) {
        myclass mc = new myclass(args[0]);
        mc.processFiles();
    }
}

在 C++ 中,我有:

JNIEXPORT void JNICALL Java_myclass_processFiles(JNIEnv *env, jobject obj) {
    jclass baseClass = env->GetObjectClass(obj);
    jfieldID fid = env->GetFieldID(baseClass, "file", "Ljava/lang/String;");
    jchar filename = env->GetCharField(baseClass, fid);
    jstring fileFieldString = env->NewString(&filename, sizeof(filename));
    const char *nativeFileString = env->GetStringUTFChars(fileFieldString, NULL);
    printf("JNI: File path: %s\n", nativeFileString);
    env->ReleaseStringUTFChars(fileFieldString, nativeFileString);
}

我的输出是:

JNI: File path: ??2

我做错了什么没有正确地将 Java 字符串转换为 char* 字符串?我提供路径 ~/Desktop/myfile 作为唯一参数,因此 args[0] 中有一个值。我的想法是 sizeof(filename) 不对,但据我所知没有其他选择。

我确实尝试过:JNI. How to get jstring from jobject and convert it to char* 但是当我将 GetObjectField() 的结果类型转换为 jstring 时,我收到一个错误:

# A fatal error has been detected by the Java Runtime Environment:
#
#  SIGSEGV (0xb) at pc=0x00000001043111e8, pid=6191, tid=3591
#
# JRE version: Java(TM) SE Runtime Environment (8.0_45-b14) (build 1.8.0_45-b14)
# Java VM: Java HotSpot(TM) 64-Bit Server VM (25.45-b02 mixed mode bsd-amd64 compressed oops)
# Problematic frame:
# V  [libjvm.dylib+0x3111e8]  jni_GetStringUTFChars+0x66
#
# Failed to write core dump. Core dumps have been disabled. To enable core dumping, try "ulimit -c unlimited" before starting Java again

另外,这只是 OSX 上的 JNI 和 Java 8,与 Android 无关。

谢谢。

更新: 我能够让一个朋友看它,并让它与它一起工作:

jfieldID fid = env->GetFieldID(baseClass, "file", "Ljava/lang/String;");
jstring jstr = (jstring) env->GetObjectField(thiz, fid);
const char *nativeFileString = env->GetStringUTFChars(jstr, NULL);
printf("JNI: File path: %s\n", nativeFileString);

【问题讨论】:

  • 只需将其作为参数传递给 JNI 方法即可。尽量不要多写一行 JNI。

标签: java c++ java-native-interface


【解决方案1】:

你在做jchar filename = env->GetCharField(baseClass, fid);

但是fid 是Ljava/lang/String; 类型的字段,而不是char。因此,您应该使用env->GetObjectField() 获取String,然后按照该链接的说明进行操作。

您还可以通过在每一行之后添加env->ExceptionDescribe() 来更好地调试它,以查看在您调用env 之后是否抛出Exception(这只是为了调试,在实际生产代码中您应该检查对于每次env 调用后的异常情况,如果出现问题,请执行某些操作)。

顺便说一句,也许您的代码只是一个示例,但如果那是您的真实代码,将native 方法声明为static 并将字符串作为参数传递会容易得多。

【讨论】:

  • 我能够让它工作,GetObjectField() 是合适的函数。
猜你喜欢
  • 2023-03-23
  • 1970-01-01
  • 1970-01-01
  • 2017-06-08
  • 1970-01-01
  • 1970-01-01
  • 2022-11-16
  • 1970-01-01
  • 2018-02-01
相关资源
最近更新 更多