JNI (5) the invocation API

Source: Internet
Author: User
Tags reserved

The calling API allows software providers to load Java VMS into arbitrary local applications. Vendors can provide Java-enabled applications without the need to link Java VM code. Overview

The following code shows how to use a function by invoking the API. In this example, C + + code creates a Java VM and invokes a static method, which is main.test. For code simplicity, error checking is omitted.

    #include <jni.h>/* where everything is defined/   &nbsp ...     jav       AVM *JVM;       /* denotes a Java VM */    jnienv *env; /* Pointer to native method interface * *     javavminitargs Vm_args;
/* JDK/JRE 6 VM initialization arguments * *     javavmoption* options = new Javavmoption[1];
    options[0].optionstring = "-djava.class.path=/usr/lib/java";
    vm_args.version = jni_version_1_6;
    vm_args.noptions = 1;
    vm_args.options = options;
    vm_args.ignoreunrecognized = false;     /* load and initialize a Java VM, return a JNI interface      * pointer i
N env/&NBSP;&NBSP;&NBSP;&NBSP;JNI_CREATEJAVAVM (&AMP;JVM, (void**) &env, &vm_args);
    delete options;     /* invoke the Main.test method using the JNI */    jclass CLS = Env->findclass ("Main");
    jmethodid mid = Env->getstaticmethodid (CLS, "Test", "(I) V");
    env->callstaticvoidmethod (CLS, Mid, 100);     /* We are done.

 * * &NBSP;&NBSP;&NBSP;&NBSP;JVM-&GT;DESTROYJAVAVM ();

This example uses three methods in the interface, and the calling API allows local applications to use the JNI interface pointer to access the characteristics of the VM. Design a Jri embedded interface similar to Netscape. Create VM

The JNI_CREATEJAVAVM () method loads and initializes the Java VM and returns a pointer to the JNI interface pointer. JNI_CREATEJAVAVM () is called inside the main thread. Add to VM

The JNI interface pointer (jnienv) is valid in the current thread. If another thread wants to access it, it must first invoke Attachcurrentthread () to add itself to the VM and get the JNI interface pointer. Once added to the VM, the local thread runs and the Java thread runs in the local method. The local thread maintains a reference to the VM and knows that the Detachcurrentthread () method is invoked before the association relationship is canceled.

The additional thread stack should have enough space to perform a reasonable number of tasks. The operating system assigns the specified space to each thread. For example, using threads, the stack size can be specified by the pthread_attr_t parameter. detach A local thread from the VM to detach from the VM requires a call to Detachcurrentthread (), and the detach must be before exiting. If a Java method executes on the stack, the thread cannot detach itself. Uninstall VM

JNI_DESTROYJAVAVM () Uninstall the Java VM. As of Jdk/jre 1.1, only the main thread can invoke the DESTROYJAVAVM uninstall Java VM. As of Jdk/jre 1.2, you can call DESTROYJAVAVM uninstall VM on any thread.

The VM waits until the current thread was the only Non-daemon user thread before it actually unloads. User threads include both Java threads and attached native threads. This is restriction exists because a Java thread or attached native thread may is holding system resources, such as locks, WI Ndows, and so on. The VM cannot automatically free. By restricting the "current thread of" running thread, the VM is unloaded, the burden of releasing system re Sources held by arbitrary threads are on the programmer. Library and version management

As of JDK/JRE 1.1, once the local library is loaded, all classloader can see it. Therefore, the same local method may be linked to different two classes in a different class loader. This can result in two problems: a class may be incorrectly linked to a local library in a different class loader. Local methods can be very confusing to confuse classes loaded by different class loaders. This breaks the namespace separation provided by the ClassLoader and results in a type-safe problem.

As of Jdk/jre 1.2, each class loader manages its own local library. The same JNI local library cannot be loaded repeatedly in a class loader. If you do that, it causes Unsatisfiedlinkerror to throw, for example, the local library is typically loaded into two class loaders, and System.loadlibrary throws Unsatisfiedlinkerror. The advantage of this is that namespace separation based on the ClassLoader is stored in the local library. A native library cannot confuse classes from different ClassLoader. In addition, they unload when their corresponding ClassLoader is garbage collected.

To improve versioning and resource management, the JNI library offers the following two methods in Jdk/jre 1.2: jni_onload

Jint jni_onload (JAVAVM *vm, void *reserved);

When the native library is loaded, the VM calls Jni_onload (for example, through System.loadlibrary). Jni_onload must return the JNI version required for the original repository.

If the new JNI function, the native library jni_onload function must return jni_version_1_2. If the native library does not have jni_onload functions, then the VM assumes that the library needs jni_version_1_1. If the VM does not recognize the value returned by the Jni_onload method, the native library cannot be loaded. linkage:

Exported from native libraries this contain native method implementation. SINCE:

JDK/JRE 1.4

Using the Jni method described in j2se1.2, in addition to the functionality in JDK/JRE 1.1, the Jni_onload method of the native package must return to jni_version_1_2.

Using the Jni method described in j2se1.4, in addition to the functionality in Jdk/jre 1.2, the Jni_onload method of the native package must return to jni_version_1_4.

If the native package does not have a jni_onload function, the VM will assume that the package requires a JNI version of Jni_version_1_1. If the VM does not recognize the version number that the Jni_onload function puts back, the native package cannot be loaded. Jni_onunload

void Jni_onunload (JAVAVM *vm, void *reserved);

The VM calls the Jni_onunload function when the native package is garbage collected. This function can be used to perform cleanup operations. Because this function is invoked by an unknown context (such as from a finalizer), programmers should be conservative in using Java VM Services and avoid arbitrary Java callbacks.

Note: The JNI onload and JNI onunload are two functions originating from the JNI library, not the VM. linkage:

Exported from native libraries this contain native method implementation. Invocation API Functions

The pointer JAVAVM type invokes the API function table. The following code example shows the function table.

typedef const struct JNIINVOKEINTERFACE *JAVAVM;


const struct Jniinvokeinterface ... = {null,
    null, NULL,

    DESTROYJAVAVM,
    Attachcurrentthread,
    Detachcurrentthread,

    GETENV,

    Attachcurrentthreadasdaemon
};


Note the functions of these three calling APIs: Jni_getdefaultjavavminitargs (), Jni_getcreatedjavavms (), and JNI_CREATEJAVAVM (), not part of the JAVAVM function table. These functions can already be used before JAVAVM. Jni_getdefaultjavavminitargs

Jint Jni_getdefaultjavavminitargs (void *vm_args);

Returns the default configuration for the Java VM. Before using this function, you need to develop the version number of the JNI version (set this property vm_args->version), which indicates the JNI version number required by the VM. After this method returns, the value of the vm_args->version is the version value that the VM supports. linkage:

Exported from the native library that implements the Java virtual machine. PARAMETERS

Vm_args:a Pointer to a JAVAVMINITARGS structure into to which the default arguments are. RETURNS:

Returns JNI_OK If the requested version is supported; Returns a JNI error code (a negative number) if the requested version is not supported. Jni_getcreatedjavavms

Jint Jni_getcreatedjavavms (JAVAVM **vmbuf, Jsize Buflen, jsize *nvms);

Returns all Java VMS that have been created. Returns All Java VMs this have been created. All VM pointers are saved in the VMBUF buffer in the order in which they were created. The total number of VMS is stored in *nvms.

In Jdk/jre 1.2, creating multiple VMs in a process is supported. linkage:

Exported from the native library that implements the Java virtual machine. PARAMETERS:

Vmbuf:pointer to the buffer where the VM structures would be placed.

Buflen:the length of the buffer.

Nvms:a pointer to an integer. RETURNS:

Returns JNI_OK on success; Returns a suitable JNI error code (a negative number) on failure. JNI_CREATEJAVAVM

Jint JNI_CREATEJAVAVM (JAVAVM **p_vm, void **p_env, void *vm_args);

Loads and initializes a Java VM. The current thread becomes the main thread. Sets the JNI interface pointer of the main thread to the env parameter.

In Jdk/jre 1.2, creating multiple VMs in a process is supported.

The second argument JNI_CREATEJAVAVM always points to jnienv *, and the third parameter is a pointer Javavminitargs structure that encodes any VM startup options using the option string:

typedef struct JAVAVMINITARGS {
    jint version;

    Jint noptions;
    Javavmoption *options;
    Jboolean ignoreunrecognized;
} Javavminitargs;

VERSION at least set the type of Jni_version_1_2.options is:

typedef struct JAVAVMOPTION {
    char *optionstring;  /* The option as a string in the default platform encoding *
    /void *extrainfo
} Javavmoption;

The size of the

array is represented by the Noptions field. If ignoreunrecognized  is  JNI_TRUE, JNI_CreateJavaVM  ignores all unrecognized option strings that begin with   "X" or "_".   If ignoreunrecognized  encounters an unrecognized string for JNI_FALSE,&NBSP;JNI_CREATEJAVAVM, it will immediately return to jni_err . All Java VMS must recognize the following standard parameters:

optionstring meaning
-d<name>=<value> Set a system property
-VERBOSE[:CLASS|GC|JNI] Enable verbose output. The options can is followed by a comma-separated list of names indicating what kind of messages would be printed by the VM. For example, "-verbose:gc,class" instructs the VM to print GC and class loading related messages. Standard names INCLUDE:GC, class, and JNI. All nonstandard (vm-specific) names must the begin with "X".
vfprintf ExtraInfo is a pointer to the vfprintf hook.
Exit ExtraInfo is a pointer to the exit hook.
Abort ExtraInfo is a pointer to the abort hook.

In addition, each VM implementation may support its own set of standard option strings. Non-standard option names must begin with an "-X" or an underscore ("_"). For example, JDK/JRE supports-XMS and-XMX to allow the initial and maximum heap memory size to be specified. Options with "-X" can be run on the Java command line.

Here is the sample code to create a Java VM in JDK/JRE:

Javavminitargs Vm_args;
Javavmoption options[4];

options[0].optionstring = "-djava.compiler=none";           /* Disable JIT
/options[1].optionstring = "-djava.class.path=c:\myclasses";/* User Classes * *
options[2]. optionstring = "-djava.library.path=c:\mylibs";  /* Set Native Library path * *
options[3].optionstring = "-verbose:jni";                   /* Print jni-related messages * *

vm_args.version = jni_version_1_2;
vm_args.options = options;
Vm_args.noptions = 4;
vm_args.ignoreunrecognized = TRUE;

/* Note this in the JDK/JRE, there are no longer any need to call
 * Jni_getdefaultjavavminitargs.
 /
res = JNI_CREATEJAVAVM (&VM, (void * *) &env, &vm_args);
if (res < 0) ...
linkage:

Exported from the native library that implements the Java virtual machine. PARAMETERS:

The address of the P_VM:VM structure.

The address of the P_env:jni interface (in the main thread).

VM_ARGS:VM initialization parameters. RETURNS:

Returns JNI_OK on success; Returns a suitable JNI error code (a negative number) on failure. DESTROYJAVAVM

Jint DESTROYJAVAVM (JAVAVM *VM);

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.