JNI没有使用String初始化Class Obj

时间:2015-06-16 21:11:05

标签: string object constructor java-native-interface

下面是我的C和Java代码。 Java调用function1来收集Stringinteger并使用ResultCollector对象返回它们。 ResultCollector是外部类,换句话说,它不嵌套在ResultCollecter类中。此外,它有三个构造函数。我有其他函数可以使用带有(IF)V签名的构造函数。此外,第三个构造函数也不能正常工作(即(II)V)。

Java代码是:

package user.directory;
public class ResultCollector {
    private int err;
    private float resVal;
    private String resID;

/**
 * Signature (IF)V
 */
public ResultCollector(int err, float value) {
    this.err = err;

    this.resVal = value;
}

/**
 * Signature (II)V
 */
public ResultCollector(int err, int value) {
    this.err = err;

    this.resVal = (float) value;
}

/**
 * Signature (ILjava/lang/;)V
 */
public ResultCollector(int err, char[] id) {
    this.err = err;
    this.resID = String.copyValueOf(id);

}

public String id() {
    return resID;
}

public int err() {
    return err;
}

public float value() {
    return resVal;
}

public void setParam(int err, String id, float value) {
    this.err = err;
    this.resID = id;
    this.resVal = value;
}

}

C代码是:

JNIEXPORT jobject JNICALL Java_project_function1(
        JNIEnv *env, jobject obj, jint index) {
    jint t;
    char *id = C function to return string; 
    t = an error that is needed;


     if (c == NULL)
         // throw exception
       return NULL;

     jstring name = (*env)->NewStringUTF(env, id);

     if (name == NULL)
         // throw exception
       return NULL;

     jclass c = (*env)->FindClass(env,
        "user/directory/ResultCollector");
     jmethodID constr = (*env)->GetMethodID(env, c, "<init>", "(ILjava/lang/String;)V");

    if (constr == NULL)
    //cannot get the constructor correctly
       return NULL;

   jobject result = (*env)->NewObject(env, c, constr, t, name);
   return result;
}

我的问题是:如何初始化外部类?这段代码出了什么问题?

1 个答案:

答案 0 :(得分:1)

char[]String不同。构造函数的签名应为(I[C)V[表示数组,C表示char:

jmethodID constr = (*env)->GetMethodID(env, c, "<init>", "(I[C)V");

您还需要传递jcharArray而不是jstring。您可以像这样创建jcharArray

int len = strlen(id);
jcharArray charArray = (*env)->NewCharArray(env, len);
(*env)->SetCharArrayRegion(env, charArray, 0, len, id);

或者,您可以更改Java代码以接受String而不是char[]

public ResultCollector(int err, String id) {
    this.err = err;
    this.resID = id;    
}