JNI entry (below)

Source: Internet
Author: User
3. the Java type corresponds to the local type
In the following cases, you need to apply a reference to a Java object in a local method to use conversions between types:
1) pass parameters to the local method in the Java method;
2) create a Java object in the local method;
3) return the result to the Java Program .
There are two scenarios:
Original Java type
For example, booleans, integers, floats, and other primitive types that are transferred from Java programs to local methods can be directly used. below is the correspondence between the primitive types in Java and those in local methods:
Java local bytes (BIT)
Boolean jboolean 8, unsigned
Byte jbyte 8
Char jchar 16, unsigned
Short jshort 16
Int jint 32
Long jlong 64
Float jfloat 32
Double jdouble 64
Void void N/
That is to say, if a Boolean parameter is included in the method, the jboolean type corresponds to it in the local method. Similarly, if A jint is returned in the local method, an int type is returned in Java.
Java object
Java objects are passed as references to local methods. All references to these Java objects share a common parent type jobject (equivalent to the same as the object class in Java is the parent class of all classes ). Below are some subclasses of jobject implemented by JNI:

Figure 1: subclass of jobject
4. Access the content in the Java program in the local method
1) access the string object:
The string object passed in from the Java program corresponds to the jstring type in the local method. The jstring type is different from the char * type in C, so if you use it as char * directly, an error occurs. Therefore, you need to convert jstring to char * in C/C ++ before using jnienv. The following is an example:
Code 3:
Jniexport jstring jnicall java_prompt_getline
(Jnienv * ENV, jobject OBJ, jstring prompt)
{
Char Buf [128];
Const char * STR = (* env)-> getstringutfchars (ENV, prompt, 0 );
Printf ("% s", STR );
(* Env)-> releasestringutfchars (ENV, prompt, STR );
Here you can use the getstringutfchars method to convert the passed prompt (jstring type) to the UTF-8 format.
Note: after using the object after your conversion, You need to display the call releasestringutfchars method, let JVM release the space of the object converted to the UTF-8 string, if not displayed call, the JVM will keep saving the object and will not be recycled by the garbage collector. This will cause memory overflow.
The following are some methods to access string:
◆ Getstringutfchars converts jstring to a char in UTF-8 format *
◆ Getstringchars converts jstring to a unicode char *
◆ Releasestringutfchars release pointer to char * In UTF-8 format
◆ Releasestringchars release pointer to Unicode char *
◆ Newstringutf create a String object in UTF-8 format
◆ Newstring: Creates a String object in unicode format.
◆ Getstringutflengt get the length of char * In UTF-8 format
◆ Getstringlength: Get the length of char * In unicode format
2) access the array object:
Like a String object, jarray objects cannot be directly accessed in local methods. Instead, some jnienv pointer pointing methods are used.
Access the original Java type array:
1) Get the length of the array:
Code 4:
Jniexport jint jnicall java_intarray_sumarray
(Jnienv * ENV, jobject OBJ, jintarray ARR)
{
Int I, sum = 0;
Jsize Len = (* env)-> getarraylength (ENV, arr );
As shown in code 4, the length of the array and the common C Language The length of the retrieved array is different. Here, a jnievn function getarraylength is used.
2) Get a pointer to an array element:
Code 4:
Jint * Body = (* env)-> getintarrayelements (ENV, arr, 0 );
Use the getintarrayelements method to obtain the pointer to the ARR array element. Note that the first parameter of this function is jnienv, the second parameter is array, and the third parameter is the element starting from the array.
3) Use a pointer to retrieve the elements in array.
Code 5:
For (I = 0; I <Len; I ++ ){
Sum + = body [I];
}
The usage here is no different from the use of arrays in ordinary C.
4) release the array element reference
Code 6:
(* Env)-> releaseintarrayelements (ENV, arr, body, 0 );
It is the same as releasing a string reference in the string operation, reminding JVM to reclaim the reference of the ARR array element.
The example here uses an int array, which also corresponds to boolean, float, and so on.
Array.
Obtain the correspondence between array element pointers:
Function Array type
Getbooleanarrayelements Boolean
Getbytearrayelements byte
Getchararrayelements char
Getshortarrayelements short
Getintarrayelements int
Getlongarrayelements long
Getfloatarrayelements float
Getdoublearrayelements double
Release the correspondence between array element pointers:
Function Array type
Releasebooleanarrayelements Boolean
Releasebytearrayelements byte
Releasechararrayelements char
Releaseshortarrayelements short
Releaseintarrayelements int
Releaselongarrayelements long
Releasefloatarrayelements float
Releasedoublearrayelements double

Access a custom Java object Array
The JNI provides a separate set of functions to access elements of object arrays. You can use these functions to get and set individual object array elements.

Note: you cannot get all the object array elements at once.

• Getobjectarrayelement returns the object element at a given index.
• Setobjectarrayelement updates the object element at a given index.
3) methods for accessing Java objects:
To call a Java object method in a local method:
①. Get the class of the Java object you want to access:
Jclass CLS = (* env)-> getobjectclass (ENV, OBJ );
Use the getobjectclass method to obtain the jclass corresponding to OBJ.
②. Obtain methodid:
Jmethodid mid = (* env)-> getmethodid (ENV, CLS, "Callback", "(I) V ");
Use the getmethdoid method to obtain the methdoid of the method you want to use. The parameter meanings:
Env ???> Jnienv
CLS ???> The jclass obtained in step 1
"Callback" ???> Name of the method to be called
"(I) V" ???> Signature of the Method
③. Call method:
(* Env)-> callvoidmethod (ENV, OBJ, mid, depth );
Call a method using the callvoidmethod method. Parameter meaning:
Env ???> Jnienv
OBJ ???> Jobject passed through the local method
Mid ???> Methodid to be called (that is, the methodid obtained in the second step)
Depth ???> Parameters required by the method (corresponding to the requirements of the method, add the corresponding parameters)
Note: The callvoidmethod method is used here, because there is no return value. If there is a return value, use the corresponding method, which will be mentioned later.
Signature of the Method
The signature of a method is composed of the parameters of the method and the type of the returned value. Their structure is as follows:
"(Argument-types) Return-type"
The parameter types and their values in the Java program are as follows:
Type in signature Java
Z Boolean
B byte
C char
S short
I int
J long
F float
D double
L fully-qualified-class; fully-qualified-class
[Type []
(Arg-types) ret-type method type
The signature of a Java method can be obtained through the javap command:
Javap-s-p Java class name
Pass parameters to the called function:
We usually add the parameters to be passed after methodid, but there are other methods to pass the parameters:
Callvoidmethodv can obtain a variable quantity list as a parameter;
Callvoidmethoda can obtain a union.
Call static methods:
The method called in step 2 and Step 3 is changed to the corresponding one:
Getstaticmethodid: obtains the ID of the corresponding static method.
Callstaticintmethod call static method
Call the superclass method:
I have read it for myself. ^_^.
4) Access Java object attributes:
The attribute for accessing a Java object is basically the same as the method for accessing a Java object. You only need to change the method in the function to field (of course there are other differences ).

In addition, the command to get the signature of the attribute is as follows:
Javap-s-p Java class name
5. Capture and handle exceptions
Java has a classic try, catch, and finally to handle exceptions, but there is no corresponding Exception Handling Mechanism in C or C ++. But what if a method declares that an exception is thrown? Therefore, you must check for exceptions after calling JNI where exceptions may occur. Therefore, JNI provides some functions that can throw exceptions when exceptions occur.
Steps:
1) declared exception
JNI provides jthrowable as an exception. Its declaration is as follows:
Jthrowable exc;
2) Check where exceptions need to be checked
Exc = (* env)-> predictionoccurred (ENV );
3) determine whether exc exists and handle exceptions
Jclass newexccls;
(* Env)-> predictiondescribe (ENV );
(* Env)-> predictionclear (ENV );

Newexccls = (* env)-> findclass (ENV, "Java/lang/illegalargumentexception ");
If (newexccls = 0) {/* Unable to find the new exception class, give up .*/
Return;
}
(* Env)-> thrownew (ENV, newexccls, "thrown from C Code ");
4) if exc does not exist, continue.
6. Local and global references
Pai_^
7. Thread and local method
1) thread and JNI
There are several notes:
The JNI interface pointer jnienv * is valid only in this thread;
Local references cannot be uploaded to other threads;
Pay attention to synchronization when using global references.
2) synchronization in the local method
Define synchronization block start
(* Env)-> monitorenter (ENV, OBJ );
.../* Synchronization block */
End of a synchronization Block
(* Env)-> monitorexit (ENV, OBJ );
In Java
Synchronized (OBJ ){
.../* Synchronized block */
...
}
Has the same effect.
3) WAIT AND POLICY
In Java, object. Wait, object. Policy, and object. policyall are very useful in multithreading, but JNI does not support these methods. Therefore, if you need to use the functions of these methods, you can call them by calling the Java object method.

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.