5

如何将jstring来自 JNIC代码的 a 发送到Java接收 aString作为参数的函数?

我已经阅读过类似的功能,callVoidMethodA(....)但它们不接受诸如jstring.

4

2 回答 2

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 );
}
于 2012-10-14T08:51:21.540 回答
0
JNIEXPORT jstring JNICALL 
 Java_Prompt_getLine(JNIEnv *env, jobject obj)
 {
     char *buf = "Hi !!!!";
     jstring jString = (*env)->NewStringUTF(env, buf);
     free(buf);
     return jString;
 }
于 2012-10-13T11:59:36.247 回答