NDK笔记--C++调用java
Posted ljt2724960661
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了NDK笔记--C++调用java相关的知识,希望对你有一定的参考价值。
这一节主要了解从C/C++调用java的过程,一般是用在android与Native交互的场景中,在调用过程中,一般需要C/C++层持有Java的对象,然后调用相关方法,如下
Java:
static
System.loadLibrary("ndkplay");
package com.sky.ndkplay;
public class Employee
public String name;
public int age;
public String getName()
return name;
public void setName(String name)
this.name = name;
public int getAge()
return age;
public void setAge(int age)
this.age = age;
@Override
public String toString()
return "Employee" +
"name='" + name + '\\'' +
", age=" + age +
'';
public class MainActivity extends AppCompatActivity
// Used to load the 'ndkplay' library on application startup.
static
System.loadLibrary("ndkplay");
private ActivityMainBinding binding;
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
binding = ActivityMainBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
public native void insertObject();
public void showEmployeeInfo(View view)
insertObject();
extern "C"
JNIEXPORT void JNICALL
Java_com_sky_ndkplay_MainActivity_insertObject(JNIEnv *env
,jobject instance)
jclass employee_class = env->FindClass("com/sky/ndkplay/Employee");
jobject employee_obj = env->AllocObject(employee_class);
jmethodID setName = env->GetMethodID(employee_class,"setName","(Ljava/lang/String;)V");
jmethodID setAge = env->GetMethodID(employee_class,"setAge","(I)V");
jstring strRes = env->NewStringUTF("lisi");
env->CallVoidMethod(employee_obj,setName,strRes);
env->CallVoidMethod(employee_obj,setAge,100);
以上是关于NDK笔记--C++调用java的主要内容,如果未能解决你的问题,请参考以下文章