从jni c代码发送jstring到接收字符串作为参数的java函数

时间:2012-10-13 11:39:02

标签: java c string java-native-interface

如何将jstring从JNI C代码发送到接收Java作为参数的String函数?

我已阅读有关callVoidMethodA(....)等功能的内容,但他们不接受任何内容,例如jstring

2 个答案:

答案 0 :(得分:3)

您尚未提及目标类名称和目标方法签名。例如,考虑java.lang.StringBuilder.append(java.lang.String)方法。

// First lets assume you have already received the next variables
void foo( JNIEnv* env, jobject obj )
{
    // Call StringBuilder.append() method
}

现在您需要类名和方法签名(根据docs

static char const StringBuilder_ClassName = "java/lang/StringBuilder";
static char const StringBuilder_append_MethodName = "append";
static char const StringBuilder_append_MethodSignature =
    "(Ljava/lang/String;)Ljava/lang/StringBuilder;";

要从JNI代码调用java方法,您应该获得jmethodID

static jclass StringBuilder_Class = 0;
static jmethodID StringBuilder_append_Method = 0;

void Init( JNIEnv* env )
{
     if( StringBuilder_Class == 0 ) {
         StringBuilder_Class = (*env)->FindClass( env, StringBuilder_ClassName );
         // TODO: Handle error if class not found
     }
     if( StringBuilder_append_Method == 0 ) {
         StringBuilder_append_Method = (*env)->GetMethodID( env, StringBuilder_Class,
             StringBuilder_append_MethodName, StringBuilder_append_MethodSignature );
         // TODO: Handle error if method not found
     }
}

void foo( JNIEnv* env, jobject obj )
{
    Init();
    char* str;
    // str = ...;
    jstring jString = (*env)->NewStringUTF( env, str );
    // Because StringBuild.append() returns object, you should call CallObjectMethod
    jobject ret = (*env)->CallObjectMethod( env, obj, jString );
    // Here you can release local references, i.e.
    // (*env)->DeleteLocalRef( env, ret );
    // (*env)->DeleteLocalRef( env, jString );
    // But it is not necessary. Local references are released automatically when
    // thread returns from JNI code to Java code.
    // So you can ignore the returned value and not to release the jString local
    // reference, i.e. just call
    // (*env)->CallObjectMethod( env, obj, jString );
}

答案 1 :(得分:1)

JNIEXPORT jstring JNICALL 
 Java_Prompt_getLine(JNIEnv *env, jobject obj)
 {
     char *buf = "Hi !!!!";
     jstring jString = (*env)->NewStringUTF(env, buf);
     free(buf);
     return jString;
 }