JNI 通过形参String返回数据的方法

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

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

package com.zkzh.alpr.jni;

public class Decodec {

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

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

}
#include 
#include 

/*
 * 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, "Cosmo 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, "Cosmo 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, "Cosmo 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(outputJobj, appendJmId, _jstring);


    env->ReleaseStringUTFChars(inputStrJstr, pInputStr);

    return 0;
}


 

使用方法:

StringBuffer output = new StringBuffer();

Codec.test("Cosmo is Wangzy", output);

Log.e("Cosmo", "output:" + output);

你可能感兴趣的:(JNI)