JNI通过形参返回String的方法

梦想的初衷 提交于 2020-04-06 13:30:48

标题虽说是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);

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!