JNI Java的基本调用
作者:互联网
接口的作用无非就是取值、传参、方法调用之类的东西。
Android studio默认的native项目就是调用JNI的方法。
在JNI中怎么调用java类的属性,方法;以下为基本示例:
public class MainActivity extends AppCompatActivity {
public int javaNum=3;
// Used to load the 'native-lib' library on application startup.
static {
System.loadLibrary("native-lib");
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Example of a call to a native method
TextView tv = findViewById(R.id.sample_text);
tv.setText(stringFromJNI());
Log.d("TAG", "JNI_log onCreate: ...."+javaNum);
}
public void javaMethod(String log){
Log.d("TAG", "javaMethod call:...... "+log);
}
/**
* A native method that is implemented by the 'native-lib' native library,
* which is packaged with this application.
*/
public native String stringFromJNI();
}
cplusplus:
#include <jni.h>
#include <string>
#include<android/log.h>
#define TAG "JNI_log" // 这个是自定义的LOG的标识
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,TAG ,__VA_ARGS__) // 定义LOGD类型
//jni 调用获取/赋值java属性(变量)
int getAndSetField(JNIEnv *env,
jobject thiz/* this */) {
//1.获取
jclass clz = env->GetObjectClass(thiz);
//2.获取属性id
jfieldID myNum = env->GetFieldID(clz, "javaNum", "I");
LOGD("获取属性id jfieldID = %d", myNum);
//3.取值 ps:如果属性域是静态的,那么使用方法GetStaticFieldID, GetStaticObjectField
int value = env->GetIntField(thiz, myNum);
LOGD("获取属性值 value = %d", value);
//4.改值
env->SetIntField(thiz, myNum, 6);
env->DeleteLocalRef(clz);
return 1;
}
//jni 访问java方法
void callJavaMethod(JNIEnv *env,jobject thiz/* this */){
jclass clz = env->GetObjectClass(thiz);
//1.获取方法属性id
jmethodID javaMethod = env->GetMethodID(clz, "javaMethod","(Ljava/lang/String;)V");
//2.调用方法,传递参数
const char *msg = "from native";
jstring jmsg = env->NewStringUTF(msg);
env->CallVoidMethod(thiz,javaMethod,jmsg);
env->DeleteLocalRef(clz);
}
void test(JNIEnv *env,jobject thiz){
getAndSetField(env, thiz);
callJavaMethod(env,thiz);
}
extern "C" JNIEXPORT jstring JNICALL
Java_com_example_myapplication_MainActivity_stringFromJNI(
JNIEnv *env,
jobject thiz /* this */) {
std::string hello = "Hello from C++";
test(env, thiz);
return env->NewStringUTF(hello.c_str());
}
附个比较全的用法示例:JNI 常见用法 - 简书
标签:thiz,调用,Java,clz,javaMethod,env,JNI,native 来源: https://blog.csdn.net/qiaoyl113/article/details/121857102