【发布时间】: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