JNI通过形参返回String的方法

原创
2020/03/30 10:19
阅读数 3.6K

标题虽说是String但实际使用了StringBuffer

很简单,往下看吧,直接cp过去就可以用了。

public class Decodec {

    public static native int test(String inPut, StringBuffer outPut);

    static {
        System.loadLibrary("decodec");
    }

}
 

#include <android/log.h>
#include <string.h>

/*
 * Class:     jp_ac_jaist_myjnitest_Codec
 * Method:    test
 * Signature: (Ljava/lang/String;Ljava/lang/StringBuffer;)I
 */
JNIEXPORT jint JNICALL Java_jp_ac_jaist_myjnitest_Codec_test
  (JNIEnv* env, jclass, jstring inputStrJstr, jobject outputJobj)
{
    const char* pInputStr = env->GetStringUTFChars(inputStrJstr, JNI_FALSE);
    if (pInputStr == NULL)
    {
        return -1;
    }

    __android_log_print(ANDROID_LOG_DEBUG, "Test", "pInputStr:%s", pInputStr);


    jclass outputJcls = env->GetObjectClass(outputJobj);
    if (outputJcls == NULL)
    {
        __android_log_print(ANDROID_LOG_DEBUG, "Cosmo Test", "Unable to find outputJcls");
        return -1;
    }

    jfieldID valueJfId = env->GetFieldID(outputJcls, "value", "[C");
    if (valueJfId == NULL)
    {
        __android_log_print(ANDROID_LOG_DEBUG, "Test", "Unable to get class StringBuffer.value's jfieldID");
        return -1;
    }
    jmethodID appendJmId = env->GetMethodID(outputJcls, "append", "(Ljava/lang/String;)Ljava/lang/StringBuffer;");
    if (appendJmId == NULL)
    {
        __android_log_print(ANDROID_LOG_DEBUG, "Test", "Unable to find appendJmId");
    }

    char name[200];
    memset(name, 0x00, sizeof(name));

    strncpy(name, "Cosmo Wang", sizeof(name) - 1);

    jstring _jstring = env->NewStringUTF(name);

    env->CallObjectMethod(outPut, appendJmId, _jstring);


    env->ReleaseStringUTFChars(inputStrJstr, pInputStr);

    return 0;
}
 

使用方法:

StringBuffer output = new StringBuffer();
 
Codec.test("hello", output);
 
Log.e("Test", "output:" + output);

 

展开阅读全文
加载中
点击引领话题📣 发布并加入讨论🔥
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部