从本机代码调用另一个包的静态 java 方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7238429/
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
Call a static java method of another package from native code
提问by Tom
For example, let's say that in Android, I need to call the static method android.os.SystemClock.elapsedRealtime()
, which returns a long, from a portion of native code. In the mylib.c
file, I have
例如,假设在 Android 中,我需要android.os.SystemClock.elapsedRealtime()
从本机代码的一部分调用静态方法,该方法返回一个长整数。在mylib.c
文件中,我有
JNIEXPORT jlong JNICALL
Java_com_mpackage_MyClass_nativeMethod(JNIEnv *env, jobject obj){
jclass cls = (*env)->GetObjectClass(env, obj);
jmethodID mid = (*env)->GetStaticMethodID(env, cls, "android.os.SystemClock.elapsedRealtime", "(V)J");
if (mid == 0)
return 0L;
return CallStaticLongMethod(cls, mid);
}
In the java MyClass.class
, I have among others
在 java 中MyClass.class
,我有
static {System.loadLibrary("myLib");}
native long nativeMethod();
but when I call it, I get the following error:
但是当我调用它时,出现以下错误:
ERROR/AndroidRuntime(628): java.lang.NoSuchMethodError:
android.os.SystemClock.elapsedRealtime()
at the declaration of mid
line. I think this is straightforward but I'm new to jni.
在行的声明处mid
。我认为这很简单,但我是 jni 的新手。
Can someone point out my mistake(s)?
有人可以指出我的错误吗?
采纳答案by bobby
Looks like your usage of the JNI API is not proper.
First you should get the class reference of android.os.SystemClock
. The obj passed as a parameter, is an object of MyClass
. You should use (*env)->FindClass(env, "android/os/SystemClock")
to get a jclass for the SystemClock. Then call (*env)->GetStaticMethodID(env, cls,"elapsedRealtime", "(V)J");
to get the method id. Take a look at the JNI tutorialfor further details
看起来您对 JNI API 的使用不正确。首先,您应该获得android.os.SystemClock
. 作为参数传递的 obj 是 的对象MyClass
。您应该使用(*env)->FindClass(env, "android/os/SystemClock")
来获取 SystemClock 的 jclass。然后调用(*env)->GetStaticMethodID(env, cls,"elapsedRealtime", "(V)J");
获取方法id。查看JNI 教程以获取更多详细信息