jni返回复杂对象

来源:互联网 发布:电视剧直播软件 编辑:程序博客网 时间:2024/05/14 22:35

很多时候写jni接口需要给java层返回复杂对象,如下面的java对象:



public class MapPoI {    private int linkid ;    private String name ;    private float x ;    private float y ;    private int m_type;    //构造函数,什么都不做    public MapPoI(){ }    public MapPoI(String name, int linkid , float x, float y, int m_type){        this.linkid = linkid ;        this.name = name ;        this.x = x ;        this.y = y ;        this.m_type = m_type;    }
}


jni层:

JNIEXPORT jobject JNICALL Java_com_zongmu_valetparking_mapjni_MapJni_getMapPoiList(JNIEnv *env, jclass type,  jint poi_type_) {    std::vector<MapPOI>  foundPoIs; //用来接收C++ vector 列表    foundPoIs =  ZMMap::Instance()->GetPOI();    int count = foundPoIs.size();    jclass list_cls = env->FindClass("java/util/ArrayList");//获得ArrayList类引用    jmethodID list_costruct = env->GetMethodID(list_cls , "<init>","()V"); //获得得构造函数Id    jobject list_obj = env->NewObject(list_cls , list_costruct); //创建一个Arraylist集合对象    //或得Arraylist类中的 add()方法ID,其方法原型为: boolean add(Object object) ;    jmethodID list_add  = env->GetMethodID(list_cls,"add","(Ljava/lang/Object;)Z");    jclass stucls = env->FindClass("com/zongmu/valetparking/model/MapPoI");//获得mappoi类引用    //获得该类型的构造函数  函数名为 <init> 返回类型必须为 void 即 V    jmethodID stu_costruct = env->GetMethodID(stucls , "<init>", "(Ljava/lang/String;IFFI)V");    //注意 (Ljava/lang/String;IFFI)V  表示对象参数类型:string,int,float ,数量类型必须一致,douable为D booleanZbyteBcharCshortSintIlongJfloatFdoubleDvoidV      for(int i = 0 ; i < count ; i++)     {        jstring name = env->NewStringUTF(foundPoIs[i].m_name.c_str());        int link_id = foundPoIs[i].m_linkID;        float x = foundPoIs[i].m_pos.x();        float y = foundPoIs[i].m_pos.y();        int m_type = foundPoIs[i].m_type;        LOG_ERROR("MapPOI x= %10f, y = %l0f ,name = %s,m_type = %d,link_id = %d",x,y,foundPoIs[i].m_name.c_str(),m_type,link_id,m_type);        //通过调用该对象的构造函数来new 一个 Mappoi实例        jobject stu_obj = env->NewObject(stucls ,stu_costruct ,name,link_id,x,y);  //构造一个对象        env->CallBooleanMethod(list_obj , list_add , stu_obj); //执行Arraylist类实例的add方法,添加一个stu对象        env->DeleteLocalRef(stu_obj);    }    env->DeleteLocalRef(list_cls);    env->DeleteLocalRef(stucls);    return list_obj ;}


java层调用:

ArrayList<MapPoI> poiList = MapJni.getMapPoiList(0);Log.d("ZmMapView","返回列表长度  listsize = "+poiList.size());for(int i = 0 ; i < poiList.size() ; i++){    Log.d("ZmMapView"," 第 "+i+" 条POI信息 "+poiList.get(i).toString());}



原创粉丝点击