从JNI获取Java中使用的字符串

Vik*_*yan 4 c java java-native-interface android

JAVA代码

下面是我的一些代码的一部分,我已经写在JAVA,正如你可以看到这是一个叫做类JC_VerificationCandidate是有两个String成员enrollmentIDseedIndex.

class JC_VerificationCandidate {

    public JCDSM_VerificationCandidate( String enrollmentID, String seedIndex ) {
        this.enrollmentID = enrollmentID;
        this.seedIndex    = seedIndex;
    }

    public String enrollmentID;
    public String seedIndex;
}
Run Code Online (Sandbox Code Playgroud)

这里是主要类,我有本机方法,从那里我称之为本机方法.

public class DsmLibraryTest extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {

        JCDSM_VerificationCandidate verificationCandidate[] = {new JCDSM_VerificationCandidate( "tom", "anna" )}; 
        dsm.JDSMVerify( 123456, "http:\\www.test_url.com", bytes, verificationCandidate );

    }

    public native int JDSMVerify(
                   int                         someValue1,
                   String                      someValue2,
                   byte[]                      someValue3,
                   JC_VerificationCandidate    jVerificationCandList[] );
}
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,我使用一个对象创建数组并将其提供给我的函数.

JCDSM_VerificationCandidate verificationCandidate[] = {new JCDSM_VerificationCandidate( "tom", "anna" )};
Run Code Online (Sandbox Code Playgroud)

JNI代码

我怎样才能得到这两个字符串enrollmentID,eedIndex我已经从Java应用程序中设置并存储在jVerificationCandList

JNIEXPORT jint JNICALL Java_com_Dsm_Test_DSM_JDSMVerify( JNIEnv* env, jobject thiz, jint jhDevice, jstring jurlID,
                                                         jbyteArray jInputInfo, jobjectArray jVerificationCandList ) {


}
Run Code Online (Sandbox Code Playgroud)

Rob*_*ert 8

以下代码应允许您访问字段enrollmentID.使用JNI字符串函数来读取/操作它们.

// Load the class
jclass jclass_JCV = env->FindClass(env, "my.package.JC_VerificationCandidate");

jfieldID fid_enrollmentID = env->GetFieldID(env, jclass_JCV, "enrollmentID" , "Ljava/lang/String;");

// Access the first element in the jVerificationCandList array 
jobject jc_v = env->GetObjectArrayElement(env, jVerificationCandList, 0);

// get reference to the string 
jstring jstr = (jstring) env->GetObjectField(env, jc_v, enrollmentID);

// Convert jstring to native string
const char *nativeString = env->GetStringUTFChars(env, jstr, 0);
Run Code Online (Sandbox Code Playgroud)

  • const char*nativeString =(*env) - > GetStringUTFChars(env,jstr,0); 好的 !!!就这样 !! (5认同)
  • 不要忘记稍后释放它,否则你会泄漏。(*env)->ReleaseStringUTFChars(...) (2认同)