JNI調(diào)用java自定義類

一部脚,注冊(cè)java方法和jni方法相對(duì)應(yīng)

 static const JNINativeMethod gMethods[] = {
        //name   //signature   //funcPtr
        {"testObjectJNI","(Lcom/zero/sdk/jnitest/TestMsg;)I",(void *)jni_test},
};


JNIEXPORT jint JNI_OnLoad(JavaVM* vm, void* reserved){
    JNIEnv* env = NULL;
    if(vm->GetEnv((void**)&env, JNI_VERSION_1_4) != JNI_OK) //從JavaVM獲取JNIEnv灸拍,一般使用1.4的版本
        return -1;
    jclass clazz = env->FindClass(JAVA_CLASS_PATH);
    if (!clazz){
        LOGW("cannot get class");
        return -1;
    }
    if(env->RegisterNatives(clazz, gMethods, sizeof(gMethods)/sizeof(gMethods[0])))
    {
        LOGW("register native method failed!");
        return -1;
    }
    return JNI_VERSION_1_4;
}

二,通過接口傳遞java類
java定義接口

 private native int testObjectJNI(TestMsg responseMsg)

c++定義接口

static jint jni_test(JNIEnv* pEnv, jobject , jobject arg)
{}

三型诚,java層創(chuàng)建對(duì)象傳遞并通過native接口傳遞到c++層

TestMsg testMsg = new TestMsg();
testMsg.msg = "server is hungry!";
testMsg.subTestMsg = new TestMsg.SubTestMsg();
testObjectJNI(testMsg); //調(diào)用native通信接口
System.out.println("=================code:"+testMsg.code+";msg:"+ testMsg.msg+";subMsg:"+testMsg.subTestMsg.subMsg);

四,c++層獲取java類以及其成員數(shù)據(jù)并修改設(shè)置

const char* buf  = "code is success";
const char* subBuf  = "sub code is success";

static jint jni_test(JNIEnv* pEnv, jobject , jobject arg)
{
    jclass jcarg =GetClassOrDie(pEnv,arg);
    jfieldID iid = GetFieldIDOrDie(pEnv,jcarg, "code", "I");
    pEnv->SetIntField(arg,iid,200);
    jfieldID strid = GetFieldIDOrDie(pEnv,jcarg, "msg", "Ljava/lang/String;");

    SetChar2JString(pEnv,arg,strid,buf);

    jfieldID subMsgId = GetFieldIDOrDie(pEnv,jcarg,"subTestMsg","Lcom/zero/sdk/jnitest/TestMsg$SubTestMsg;");
    if (!subMsgId){
        LOGW("===========================subMsgId is null");
    }
    jobject subObj = pEnv->GetObjectField(arg, subMsgId);

    if (!subObj){
        LOGW("===========================subObj is null");
    }

    jclass subClass = FindClassOrDie(pEnv,"com/zero/sdk/jnitest/TestMsg$SubTestMsg");
    if (!subClass) {
        LOGW("===========================findClass is null");
    }
    jfieldID subStrid = GetFieldIDOrDie(pEnv,subClass,"subMsg", "Ljava/lang/String;");
    if (!subStrid){
        LOGW("===========================subStrid is null");
    }

    SetChar2JString(pEnv,subObj,subStrid,subBuf);

    return 0;
}

附完整實(shí)現(xiàn)code:
c++實(shí)現(xiàn)接口

#include <jni.h>
#include <string>
#include <android/log.h>
#include "core_jni_helpers.h"


#define TAG "SceneManager" // 這個(gè)是自定義的LOG的標(biāo)識(shí)
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,TAG ,__VA_ARGS__) // 定義LOGD類型
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO,TAG ,__VA_ARGS__) // 定義LOGI類型
#define LOGW(...) __android_log_print(ANDROID_LOG_WARN,TAG ,__VA_ARGS__) // 定義LOGW類型
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR,TAG ,__VA_ARGS__) // 定義LOGE類型
#define LOGF(...) __android_log_print(ANDROID_LOG_FATAL,TAG ,__VA_ARGS__) // 定義LOGF類型



extern "C" JNIEXPORT jstring JNICALL
Java_com_zero_sdk_jnitest_MainActivity_stringFromJNI(
        JNIEnv *env,
        jobject obj) {
    std::string hello = "Hello from C++";
    jstring jstr = env->NewStringUTF(hello.c_str());
    return jstr;
}

const char* SCENE_REMOTE_PROXY_PATH = "com/zero/sdk/jnitest/MainActivity";
const char* buf  = "code is success";
const char* subBuf  = "sub code is success";

static jint jni_test(JNIEnv* pEnv, jobject , jobject arg)
{
    jclass jcarg =GetClassOrDie(pEnv,arg);
    jfieldID iid = GetFieldIDOrDie(pEnv,jcarg, "code", "I");
    pEnv->SetIntField(arg,iid,200);
    jfieldID strid = GetFieldIDOrDie(pEnv,jcarg, "msg", "Ljava/lang/String;");

    SetChar2JString(pEnv,arg,strid,buf);

    jfieldID subMsgId = GetFieldIDOrDie(pEnv,jcarg,"subTestMsg","Lcom/zero/sdk/jnitest/TestMsg$SubTestMsg;");
    if (!subMsgId){
        LOGW("===========================subMsgId is null");
    }
    jobject subObj = pEnv->GetObjectField(arg, subMsgId);

    if (!subObj){
        LOGW("===========================subObj is null");
    }

    jclass subClass = FindClassOrDie(pEnv,"com/zero/sdk/jnitest/TestMsg$SubTestMsg");
    if (!subClass) {
        LOGW("===========================findClass is null");
    }
    jfieldID subStrid = GetFieldIDOrDie(pEnv,subClass,"subMsg", "Ljava/lang/String;");
    if (!subStrid){
        LOGW("===========================subStrid is null");
    }

    SetChar2JString(pEnv,subObj,subStrid,subBuf);

    return 0;
}


static const JNINativeMethod gMethods[] = {
        //name   //signature   //funcPtr
        {"testObjectJNI","(Lcom/zero/sdk/jnitest/TestMsg;)I",(void *)jni_test},
};


JNIEXPORT jint JNI_OnLoad(JavaVM* vm, void* reserved){
    JNIEnv* env = NULL;
    if(vm->GetEnv((void**)&env, JNI_VERSION_1_4) != JNI_OK) //從JavaVM獲取JNIEnv鸳劳,一般使用1.4的版本
        return -1;
    jclass clazz = env->FindClass(SCENE_REMOTE_PROXY_PATH);
    if (!clazz){
        LOGW("cannot get class SceneRemoteProxy");
        return -1;
    }
    if(env->RegisterNatives(clazz, gMethods, sizeof(gMethods)/sizeof(gMethods[0])))
    {
        LOGW("register native method failed!");
        return -1;
    }
    return JNI_VERSION_1_4;
}

java調(diào)用


    // 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);
        TestMsg testMsg = new TestMsg();
        testMsg.msg = "server is hungry!";
        testMsg.subTestMsg = new TestMsg.SubTestMsg();
        // ResponseMsg resMsg = returnRespose();
        testObjectJNI(testMsg);
        System.out.println("=================code:"+testMsg.code+";msg:"+ testMsg.msg+";subMsg:"+testMsg.subTestMsg.subMsg);
    }

    /**
     * A native method that is implemented by the 'native-lib' native library,
     * which is packaged with this application.
     */
    public native String stringFromJNI();

    private native int testObjectJNI(TestMsg responseMsg);

java數(shù)據(jù)結(jié)構(gòu)

package com.zero.sdk.jnitest;

public class TestMsg {
    public String msg;
    public int code;
    public SubTestMsg subTestMsg;
    public static class SubTestMsg{
        public String subMsg;
    }
}

jni 方法封裝類

/*
 * Copyright (C) 2014 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#ifndef CORE_JNI_HELPERS
#define CORE_JNI_HELPERS

// Defines some helpful functions.

#ifdef NDEBUG
#define REG_JNI(name)      { name }
    struct RegJNIRec {
        int (*mProc)(JNIEnv*);
    };
#else
#define REG_JNI(name)      { name, #name }
struct RegJNIRec {
    int (*mProc)(JNIEnv*);
    const char* mName;
};
#endif

static inline jclass FindClassOrDie(JNIEnv* env, const char* class_name) {
    jclass clazz = env->FindClass(class_name);
    return clazz;
}

static inline jclass GetClassOrDie(JNIEnv* env, jobject arg) {
    jclass jcarg = env->GetObjectClass(arg);
    return jcarg;
}

static inline jfieldID GetFieldIDOrDie(JNIEnv* env, jclass clazz, const char* field_name,
                                       const char* field_signature) {
    jfieldID res = env->GetFieldID(clazz, field_name, field_signature);
    return res;
}

static inline jmethodID GetMethodIDOrDie(JNIEnv* env, jclass clazz, const char* method_name,
                                         const char* method_signature) {
    jmethodID res = env->GetMethodID(clazz, method_name, method_signature);
    return res;
}

static inline jfieldID GetStaticFieldIDOrDie(JNIEnv* env, jclass clazz, const char* field_name,
                                             const char* field_signature) {
    jfieldID res = env->GetStaticFieldID(clazz, field_name, field_signature);
    return res;
}

static inline jmethodID GetStaticMethodIDOrDie(JNIEnv* env, jclass clazz, const char* method_name,
                                               const char* method_signature) {
    jmethodID res = env->GetStaticMethodID(clazz, method_name, method_signature);
    return res;
}

static inline void SetChar2JString(JNIEnv* env,jobject obj,jfieldID id, const char* value) {
    jstring strBuf = env->NewStringUTF(value);
    env->SetObjectField(obj, id, strBuf);
}

template <typename T>
static inline T MakeGlobalRefOrDie(JNIEnv* env, T in) {
    jobject res = env->NewGlobalRef(in);
    return static_cast<T>(res);
}




#endif  // CORE_JNI_HELPERS

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末狰贯,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子赏廓,更是在濱河造成了極大的恐慌涵紊,老刑警劉巖,帶你破解...
    沈念sama閱讀 216,744評(píng)論 6 502
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件幔摸,死亡現(xiàn)場(chǎng)離奇詭異摸柄,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)抚太,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,505評(píng)論 3 392
  • 文/潘曉璐 我一進(jìn)店門塘幅,熙熙樓的掌柜王于貴愁眉苦臉地迎上來昔案,“玉大人,你說我怎么就攤上這事电媳√ごВ” “怎么了?”我有些...
    開封第一講書人閱讀 163,105評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵匾乓,是天一觀的道長捞稿。 經(jīng)常有香客問我,道長拼缝,這世上最難降的妖魔是什么娱局? 我笑而不...
    開封第一講書人閱讀 58,242評(píng)論 1 292
  • 正文 為了忘掉前任,我火速辦了婚禮咧七,結(jié)果婚禮上衰齐,老公的妹妹穿的比我還像新娘。我一直安慰自己继阻,他們只是感情好耻涛,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,269評(píng)論 6 389
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著瘟檩,像睡著了一般抹缕。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上墨辛,一...
    開封第一講書人閱讀 51,215評(píng)論 1 299
  • 那天卓研,我揣著相機(jī)與錄音,去河邊找鬼睹簇。 笑死奏赘,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的带膀。 我是一名探鬼主播志珍,決...
    沈念sama閱讀 40,096評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼橙垢,長吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼垛叨!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起柜某,我...
    開封第一講書人閱讀 38,939評(píng)論 0 274
  • 序言:老撾萬榮一對(duì)情侶失蹤嗽元,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后喂击,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體剂癌,經(jīng)...
    沈念sama閱讀 45,354評(píng)論 1 311
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,573評(píng)論 2 333
  • 正文 我和宋清朗相戀三年翰绊,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了佩谷。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片旁壮。...
    茶點(diǎn)故事閱讀 39,745評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖谐檀,靈堂內(nèi)的尸體忽然破棺而出抡谐,到底是詐尸還是另有隱情,我是刑警寧澤桐猬,帶...
    沈念sama閱讀 35,448評(píng)論 5 344
  • 正文 年R本政府宣布麦撵,位于F島的核電站,受9級(jí)特大地震影響溃肪,放射性物質(zhì)發(fā)生泄漏免胃。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,048評(píng)論 3 327
  • 文/蒙蒙 一惫撰、第九天 我趴在偏房一處隱蔽的房頂上張望羔沙。 院中可真熱鬧,春花似錦厨钻、人聲如沸撬碟。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,683評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽呢蛤。三九已至,卻和暖如春棍郎,著一層夾襖步出監(jiān)牢的瞬間其障,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,838評(píng)論 1 269
  • 我被黑心中介騙來泰國打工涂佃, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留励翼,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 47,776評(píng)論 2 369
  • 正文 我出身青樓辜荠,卻偏偏與公主長得像火本,于是被迫代替她去往敵國和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子瓢宦,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,652評(píng)論 2 354

推薦閱讀更多精彩內(nèi)容