JNI calls Java object for Android NDK development

Source: Internet
Author: User

https://my.oschina.net/zhiweiofli/blog/114064

By using the appropriate JNI functions, you can create Java objects, get, set static (static), and instance (instance) domains, and invoke static (static) and instance (instance) functions. JNI identifies domains and methods by ID, and the ID of a domain or method is a mandatory parameter for any function that processes fields and methods.
The following table lists the JNI functions that are used to obtain static (static) and instance (instance) fields and methods. Each function accepts (as arguments) a field or a method's class, their names, symbols, and they correspond to the returned Jfieldid or Jmethodid.

Function Describe
Getfieldid Gets the ID of the domain of an instance
Getstaticfieldid Get the ID of a static domain
Getmethodid The ID of the method that gets an instance
Getstaticmethodid Get the ID of a static method

Constructs an instance of a Java object

"Lpackagename/classname;");  //创建一个class的引用jmethodID id = (*env)->GetMethodID(env, cls, "", "(D)V");  //注意这里方法的名称是"",它表示这是一个构造函数,而且构造参数是double型的jobject obj = (*env)->NewObjectA(env, cls, id, args); //获得一实例,args是构造函数的参数,它是一个jvalue*类型。

The first is to obtain a class reference for the Java Class (*ENV)->findclass (env, "lpackagename/classname;"); Note that the parameter:lpackagename/classname; , l means this is describing an object type, Packagename/classname is the object's ear class path, so be sure to end with a semicolon (;)!

Then is the Id,jmethodid ID of the FETCH function = Env->getmethodid (CLS, "", "(D) V"); The first one is the class reference you just got, the second is the name of the method, and the last one is the signature of the method .

Still don't understand? I've been so, please keep looking ...

Difficult to understand function signatures

Jninativemethod is defined as follows:

typedef struct {   const char* name;   const char* signature; void* fnPtr;} JNINativeMethod;

The first variable name is the name of the function in Java.
The second variable, signature, uses a string to describe the function's arguments and return values
The third variable, fnptr, is the function pointer, which points to the C function.

One of the more difficult to understand is the second parameter, such as
"() V"
"(II) V"
"(ljava/lang/string; ljava/lang/string;) V "


These characters are actually corresponding to the parameter type one by one of the function.
The characters in "()" represent the parameters, followed by the return values. For example, "() V" means void Func ();
"(II) V" denotes void Func (int, int);

What about the rest of it? Please see the table below:

Type Symbol
Boolean Z
Byte B
Char C
Short S
Int I
Long L
Float F
Double D
void V
Object objects Lclassname; L class name;
Arrays [Array-type [Array type]
Methods method (argument-types) Return-type (parameter type) return type

Add a little bit:

1, the method parameter or the return value is the object in Java, the signature must be "L" plus its path, but this path must be separated by "/", the custom object also uses this rule

For example java.lang.String for "java/lang/string", com.nedu.jni.helloword.Student for "lcom/nedu/jni/helloword/student;"

2. When the method parameter or the return value is an array type, precede the [

For example [I means int[],[[[d represents double[][][], that is, a few-dimensional array adds several [

Call Method 1 of the Java object in the local method, get the class of the Java object you need to access:
jclass cls = (*env)->GetObjectClass(env, obj);       // 使用GetObjectClass方法获取obj对应的jclass。 jclass cls = (*env)->FindClass(“android/util/log”) // 直接搜索类名,需要是static修饰的类。
2. Get Methodid:
"callback", "(I)V"); //GetStaticMethodID(…),获取静态方法的ID使用GetMethdoID方法获取你要使用的方法的MethdoID

The meaning of its parameters:
Env-->jnienv
Cls--> The first step to get the Jclass
"Callback"-the method name to invoke
"(I) V"--signature of the method, signed with the preceding JNI rule.

3. Call Method:
(*env)->CallVoidMethod(env, obj, mid, depth);// CallStaticIntMethod(….) , 调用静态方法

Use the Callvoidmethod method to invoke the method. The meaning of the parameter:
Env-->jnienv
Obj--> through the local method jobject
Mid--> the Methodid to invoke (that is, the Methodid obtained in the second step)
Depth--> method Required parameters (corresponding to the requirements of the method, add the corresponding parameters)

Note: The Callvoidmethod method call is used here because there is no return value and if there is a return value the corresponding method is used, which is mentioned later.

CallVoidMethod                   CallStaticVoidMethodCallIntMethod                     CallStaticVoidMethodCallBooleanMethod              CallStaticVoidMethodCallByteMethod                   CallStaticVoidMethod

Now you know a little bit about how the article begins to construct the Java object instance? Let's go deeper:

JNI manipulation of Java's string object

A string object passed from a Java program corresponds to the jstring type in the local method, and the jstring type differs from the char* in C, so if you use it directly as char*, you will get an error. Therefore, it is necessary to convert jstring to char* in C + +, which is converted using the method provided by JNIEnv.

const char *str = (*env)->GetStringUTFChars(env, jstr, 0);(*env)->ReleaseStringUTFChars(env, jstr, str);

Here, the Getstringutfchars method is used to convert the incoming prompt (jstring type) into the UTF-8 format, which can be used in the local method.
Note: After you have used the object you converted, you need to show the call to the Releasestringutfchars method, let the JVM release the space of the object converted to UTF-8 string, and if the call is not displayed, the object will be saved in the JVM. Will not be reclaimed by the garbage collector, so it will cause memory overflow.

Here are some ways that JNI accesses a string object:

    • Getstringutfchars convert jstring into UTF-8 format char*
    • Getstringchars convert jstring into Unicode format char*
    • Releasestringutfchars releasing pointers to char* in UTF-8 format
    • Releasestringchars releasing pointers to char* in Unicode format
    • Newstringutf creating a String object in UTF-8 format
    • NewString creating a Unicode-formatted string object
    • Getstringutflength gets the length of the char* in UTF-8 format
    • Getstringlength gets the length of the char* in Unicode format

Here are the methods that provide two string objects and char* for mutual transfer:

/* C + + string turn to Java jstring */JstringChartojstring(jnienv* env,Const Char* Pat){Jclass strclass = (*env)->findclass (env,"Java/lang/string"); Jmethodid Ctorid = (*env)->getmethodid (env, strclass,"","([bljava/lang/string;) V"); Jbytearray bytes = (*env)->newbytearray (env,Strlen (PAT));(*env)->setbytearrayregion (env, Bytes,0,Strlen (PAT), (jbyte*) PAT); jstring encoding = (*env)->newstringutf (env,"UTF-8");Return (jstring) (*env)->newobject (env, strclass, Ctorid, Bytes, encoding);}/* Java jstring turn to C + + char* */Char*Jstringtochar(jnienv* env, jstring jstr){char* pStr =NULL; Jclass jstrobj = (*env)->findclass (env,"Java/lang/string"); jstring encode = (*env)->newstringutf (env,"Utf-8"); Jmethodid Methodid = (*env)->getmethodid (env, Jstrobj,"GetBytes", "(ljava/lang/string;) [B"); Jbytearray ByteArray = (Jbytearray) (*env)->callobjectmethod (env, Jstr, Methodid, encode); Jsize StrLen = (*env)->getarraylength (env, ByteArray); Jbyte *jbuf = (*env)->getbytearrayelements (env, ByteArray, jni_false); if (Jbuf > 0) {pStr = (char*)malloc (StrLen + 1); if (!pstr) { return NULL;} memcpy (pStr, Jbuf, StrLen); Pstr[strlen] = 0;} env->releasebytearrayelements (ByteArray, Jbuf, 0); C13>return pStr;}             

This article transfers from Zhiweiofli's Blog, reproduced please indicate the source, thank you.

JNI calls Java object for Android NDK development

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.