C ++ calls Java

Source: Internet
Author: User

Java's cross-platform features make Java more and more popular among developers, but many complaints may also be heard: the graphic user window interface developed using Java jumps out of a console window every time it is started. This console window eclipses a lot of great interfaces. How can I prevent the Java Console window from popping up the GUI program developed through Java? In fact, many popular development environments such as JBuilder and eclipse are integrated environments developed using pure Java. These integration environments do not open a command window when they are started, because they use JNI (Java Native Interface) technology. With this technology, developers do not have to use the command line to start the Java program. You can write a local GUI program to directly start the Java program, so that you can avoid opening another command window, this makes Java programs more professional.

JNI promises that Java programs running on virtual machines can call each other with programs or class libraries written in other languages (such as C and C ++. At the same time, JNI provides a complete set of APIs that promise to directly embed the Java virtual machine into a local application. Figure 1 describes the basic structure of JNI on the sun site.

Figure 1 JNI Basic Structure Description
This article describes how to call the Java method in C/C ++, and introduces the development steps and possible difficulties and solutions based on the problems that may be involved. The tool used in this article is Java Development Kit (JDK) 1.3.1 created by Sun and the Visual C ++ 6 development environment of Microsoft.

Environment Construction
To make the following code work properly, we must establish a complete development environment. First download and install JDK 1.3.1, which is "http://java.sun.com ". Assume that the installation path is c: \ JDK. The next step is to set up the integrated development environment. Choose tools> options in Visual C ++ 6 to open option 2.

Figure 2 set the integrated development environment
Add the c: \ JDK \ include and c: \ JDK \ include \ Win32 directories to the include files directory of the development environment: add the \ JDK \ lib directory to the library files directory of the development environment. These three directories are header files and library files of some constants, structures, and methods defined by JNI. The integrated development environment has been set up, and the directory c of the dynamic link library used by the Java Virtual Machine is required to execute the program: set \ JDK \ JRE \ bin \ classic to the path environment variable of the system. It should be mentioned that some developers directly copy the DLL files used by jre to the system directory for convenience. This will not work, causing initialization of the Java Virtual Machine environment to fail (Return Value-1), because the Java virtual machine uses a relative path to find the library files and other related files used. So far, the entire JNI development environment has been set up. To make this JNI journey smooth, you must first prepare a Java class. Almost all representative attributes and methods in Java will be used in this class, such as static methods and attributes, arrays, exception throws and capturing. The Java program (Demo. Java) We define is as follows. All the code demos in this article are based on this Java program. The Code is as follows:

Package JNI. test;
/**
* This class is used to demonstrate how JNI can access various object attributes.
* @ Author liudong
*/
Public class demo {
// Demonstrate how to access static basic type attributes
Public static int COUNT = 8;
// Demonstrate Object Attributes
Public String MSG;
Private int [] counts;
Public demo (){
This ("default constructor ");
}
/**
* Demonstrate how to access the constructor
*/
Public demo (string MSG ){
System. Out. println (":" + MSG );
This. MSG = MSG;
This. Counts = NULL;
}
/**
* This method demonstrates how to access an access and process Chinese characters.
*/
Public String getmessage (){
Return MSG;
}
/**
* Demonstrate access to array objects
*/
Public int [] getcounts (){
Return counts;
}
/**
* Demonstrate how to construct an array object
*/
Public void setcounts (INT [] counts ){
This. Counts = counts;
}
/**
* Capture exceptions
*/
Public void throwexcp () throws illegalaccessexception {
Throw new illegalaccessexception ("exception occur .");
}
}
Initialize Virtual Machine
Before calling the Java method, local code must first load the Java virtual machine, and then all Java programs are executed in the virtual machine. To initialize the Java Virtual Machine, JNI provides a series of interface functions called invocation APIs. Using these APIs, you can easily load virtual machines to the memory. You can use the jint jni_createjavavm (JavaVM ** PVM, void ** penv, void * ARGs) function to create a VM ). The third parameter in JDK 1.1 always points to a jdk1 _ 1 initargs structure, which cannot be seamlessly transplanted in all versions of virtual machines. In JDK
In 1.2, a standard initialization structure javavminitargs has been used to replace jdk1_1initargs. The following are two sample codes for different versions.
  
  
Initialize a virtual machine in JDK 1.1:
# Include
Int main (){
Jnienv * env;
JavaVM * JVM;
Jdk1_1initargs vm_args;
Jint res;
/* Important: the version number must not be missed */
Vm_args.version = 0x00010001;
/* Get the default VM initialization parameter */
Jni_getdefajavjavavminitargs (& vm_args );
/* Add a custom class path */
Sprintf (classpath, "% S % C % s ",
Vm_args.classpath, path_separator, user_classpath );
Vm_args.classpath = classpath;
/* Set some other initialization parameters */
/* Create a VM */
Res = jni_createjavavm (& JVM, & ENV, & vm_args );
If (RES <0 ){
Fprintf (stderr, "can't create Java VM \ n ");
Exit (1 );
}
/* Release VM Resources */
(* JVM)-> destroyjavavm (JVM );
}
Initialize a virtual machine in JDK 1.2:
/* Invoke2.c */
# Include
Int main (){
Int res;
JavaVM * JVM;
Jnienv * env;
Javavminitargs vm_args;
Javavmoption options [3];
Vm_args.version = jni_version_1_2; // this field must be set to this value.
/* Set initialization parameters */
Options [0]. optionstring = "-djava. compiler = none ";
Options [1]. optionstring = "-djava. Class. Path = .";
Options [2]. optionstring = "-verbose: JNI"; // used to track running information
/* Version number setting cannot be missed */
Vm_args.version = jni_version_1_2;
Vm_args.noptions = 3;
Vm_args.options = options;
Vm_args.ignoreunrecognized = jni_true;
Res = jni_createjavavm (& JVM, (void **) & ENV, & vm_args );
If (RES <0 ){
Fprintf (stderr, "can't create Java VM \ n ");
Exit (1 );
}
(* JVM)-> destroyjavavm (JVM );
Fprintf (stdout, "Java VM destory. \ n ");
}
To ensure the portability of JNI code, we recommend that you use JDK 1.2 to create a virtual machine. The second parameter jnienv * env of the jni_createjavavm function is a parameter throughout the beginning and end of JNI, because almost all functions require a parameter jnienv * Env.

CATEGORY Method
After the Java Virtual Machine is initialized, you can call the Java method. To call a Java object method, follow these steps:
1. Get the class definition of the specified object (jclass)
There are two ways to get the class definition of an object: the first is to use findclass to find the corresponding class when the class name is known. Note that the class name is not the same as the Java code written at ordinary times. For example, to get the definition of the class JNI. Test. Demo, the following code must be called:

Jclass CLS = (* env)-> findclass (ENV, "JNI/test/demo"); // Replace the dot with a slash.
Then, the corresponding class definition is obtained through the object:
Jclass CLS = (* env)-> getobjectclass (ENV, OBJ );
// Where obj is the object to be referenced and its type is jobject
2. Read the definition of the method to be called (jmethodid)
Let's take a look at the methods defined in JNI:
Jmethodid (jnicall * getmethodid) (jnienv * ENV, jclass clazz, const char * Name,
Const char * sig );
Jmethodid (jnicall * getstaticmethodid) (jnienv * ENV, jclass class, const char
* Name, const char * sig );
The difference between the two functions is that getstaticmethodid is used to obtain the definition of static methods, while getmethodid is used to obtain non-static method definitions. Both functions need to provide four parameters: ENV is the JNI environment obtained by the VM initialization; the second parameter class is the class definition of the object, that is, the OBJ obtained by the first step; the third parameter is the method name. The most important parameter is the fourth parameter, which is the definition of the method. Because we know the polymorphism of Methods promised in Java, it is only through the method name that there is no way to locate a specific method, so we need the fourth parameter to specify the specific definition of the method. But how can we use a string to express the specific definition of a method? JDK has prepared a decompilation tool javap, which can be used to get the definition of each attribute and method in the class. Let's take a look at the definition of JNI. Test. Demo:

Open the command line window and run javap-s-p JNI. Test. Demo. The running result is as follows:
Compiled from demo. Java
Public class JNI. Test. Demo extends java. Lang. object {
Public static int count;
/* I */
Public java. Lang. String MSG;
/* Ljava/lang/string ;*/
Private int counts [];
/* [I */
Public JNI. Test. Demo ();
/* () V */
Public JNI. Test. Demo (Java. Lang. String );
/* (Ljava/lang/string;) V */
Public java. Lang. String getmessage ();
/* () Ljava/lang/string ;*/
Public int getcounts () [];
/* () [I */
Public void setcounts (INT []);
/* ([I) V */
Public void throwexcp () throws java. Lang. illegalaccessexception;
/* () V */
Static {};
/* () V */
}
  
  
We can see that there is a comment under each attribute and method in the class. The content that does not contain spaces in the comment is the content to be filled in with the fourth parameter (for details about the javap parameters, see the JDK help ). The following code demonstrates how to access the getmessage method of JNI. Test. Demo:

/*
Suppose we already have a JNI. Test. Demo instance obj.
*/
Jmethodid mid;
Jclass CLS = (* env)-> getobjectclass (ENV, OBJ); // get the class definition of the Instance
Mid = (* env)-> getmethodid (ENV, CLS, "getmessage", "() ljava/lang/string ;");
/* If mid is 0, the method definition cannot be obtained */
Jstring MSG = (* env)-> callobjectmethod (ENV, OBJ, mid );
/*
If the method is static, you only need to write the last Code as follows:
Jstring MSG = (* env)-> callstaticobjectmethod (ENV, CLS, mid );
*/
3. Call Method
To call a method of an object, you can use the callmethod function or callstaticmethod (static method of the callback class), depending on different return types. These methods use the definition of variable parameters. If you need parameters to access a method, you only need to enter all parameters in the Method in order. When talking about constructor access, we will demonstrate how to access constructor with parameters.

Category attributes
The attributes of the category class are basically the same as those of the category class, except that the method is changed to the attribute.
1. Get the class (jclass) of the specified object)
This step is exactly the same as the first step of the category method. For details, see the first step of the category method.
2. Definition of read class attributes (jfieldid)
In JNI, the method for getting class attributes is defined as follows:
Jfieldid (jnicall * getfieldid)
(Jnienv * ENV, jclass clazz, const char * Name, const char * sig );
Jfieldid (jnicall * getstaticfieldid)
(Jnienv * ENV, jclass clazz, const char * Name, const char * sig );
In these two functions, the first parameter is the JNI environment, clazz is the class definition, name is the property name, and the fourth parameter is also used to express the type of the property. When we used the javap tool to obtain the specific definition of a class, there were two rows as follows:

Public java. Lang. String MSG;
/* Ljava/lang/string ;*/
The content in the second line of comment is the information to be filled in with the fourth parameter, which is the same as that in the callback class method.
3. Read and set attribute values
With the attribute definition, it is easy to access the attribute value. There are several methods to read and set the attributes of the class. They are getfield, setfield, getstaticfield, and setstaticfield. For example, getobjectfield can be used to read the MSG attribute of the demo class and getstaticintfield can be used to access count. The related code is as follows:

Jfieldid field = (* env)-> getfieldid (ENV, OBJ, "MSG", "ljava/lang/string ;");
Jstring MSG = (* env)-> getobjectfield (ENV, CLS, field); // MSG is the MSG of the corresponding demo
Jfieldid field2 = (* env)-> getstaticfieldid (ENV, OBJ, "Count", "I ");
Jint COUNT = (* env)-> getstaticintfield (ENV, CLS, field2 );
Access Constructor
Many people often encounter problems in this section when they are new to JNI. After checking the entire JNI. H, they can see such a function newobject, which should be a constructor that can be used for classes. However, this function must provide the method definition of the constructor. Its type is jmethodid. From the previous content, we know that to obtain the definition of a method, we must first know the name of the method. But how can we enter the name of the constructor? In fact, the access constructor is basically the same as accessing a common class method. The only difference is that the method names are different and the method calls are different. The method name must be set to "" When constructing a struct class. The following code demonstrates how to construct a demo class instance:

Jclass CLS = (* env)-> findclass (ENV, "JNI/test/demo ");
/**
First, get the class definition through the class name, which is equivalent to the class. forname method in Java.
*/
If (CLS = 0)
Jmethodid mid = (* env)-> getmethodid (ENV, CLS, "", "(ljava/lang/string;) V ");
If (mid = 0)
Jobject demo = jenv-> newobject (CLS, mid, 0 );
/**
To access the constructor, you must use the newobject function to call the definition of the previously obtained constructor.
The above code constructs a demo instance and transmits an empty string null
*/
  
  
Array Processing
Create a new array
To create an array, we should first know the type and length of the array element. JNI defines the type of a batch of arrays, jarray and the array operation function newarray, which is the type of elements in the array. For example, to create an integer array with a size of 10 and a location value of 1-10, write the following code:

Int I = 1;
Jintarray array; // defines an array object.
(* Env)-> newintarray (ENV, 10 );
For (; I <= 10; I ++)
(* Env)-> setintarrayregion (ENV, array, I-1, 1, & I );
Access Data in the array
To access an array, you must first know the length of the array and Its element type. Now we can print each element value in the created array. The Code is as follows:
Int I;
/* Get the number of elements of the array object */
Int Len = (* env)-> getarraylength (ENV, array );
/* Obtain all elements in the array */
Jint * elems = (* env)-> getintarrayelements (ENV, array, 0 );
For (I = 0; I <Len; I ++)
Printf ("element % d is % d \ n", I, elems [I]);
Chinese Processing
The processing of Chinese characters is often a headache, especially for software developed using Java, which is even more prominent in JNI. Because all characters in Java are unicode encoded, but in local methods, for example, programs written in VC, if there is no special definition, Unicode encoding is generally not used. To enable the local method to access the Chinese characters defined in Java and the Chinese strings generated by accessing the local method in Java, I have defined two methods for mutual conversion.

· Method 1: convert a Java Chinese string to a local string
/**
The first parameter is the virtual machine environment pointer.
The second parameter is the Java string definition to be converted.
The third parameter is the memory block of the locally stored converted string.
The third parameter is the memory block size.
*/
Int jstringtochar (jnienv * ENV, jstring STR, lptstr DESC, int desc_len)
{
Int Len = 0;
If (DESC = nullstr = NULL)
Return-1;
// In VC, wchar_t is the data type used to store wide-byte characters (UNICODE ).
Wchar_t * w_buffer = new wchar_t [1024];
Zeromemory (w_buffer, 1024 * sizeof (wchar_t ));
// Use getstringchars instead of getstringutfchars
Wcscpy (w_buffer, env-> getstringchars (STR, 0 ));
Env-> releasestringchars (STR, w_buffer );
Zeromemory (DESC, desc_len );
// Call the character encoding conversion function (Win32 API) to convert Unicode to an ASCII character string
// For the use of the function widechartomultibyte, see msdn
Len = widechartomultibyte (cp_acp, 0, w_buffer, 1024, DESC, desc_len, null, null );
// Len = wcslen (w_buffer );
If (LEN> 0 & Len
· Method 2: Convert the C string to a unicode string that can be recognized by Java
Jstring newjstring (jnienv * ENV, lpctstr Str)
{
If (! Env! Str)
Return 0;
Int slen = strlen (STR );
Jchar * buffer = new jchar [slen];
Int Len = multibytetowidechar (cp_acp, 0, STR, strlen (STR), buffer, slen );
If (LEN> 0 & Len <slen)
Buffer [Len] = 0;
Jstring JS = env-> newstring (buffer, Len );
Delete [] buffer;
Return JS;
}
Exception
Because Java methods are called, Operation exception information is inevitable. These exceptions cannot be captured through the Exception Processing Mechanism of C ++, but JNI can use some functions to obtain the exception information thrown in Java. Previously, we defined a method throwexcp in the demo class. The following code accesses this method and captures the thrown exception information:

/**
Suppose we have constructed a demo instance OBJ and Its Class is defined as Cls.
*/
Jthrowable excp = 0;/* exception information definition */
Jmethodid mid = (* env)-> getmethodid (ENV, CLS, "throwexcp", "() V ");
/* If mid is 0, the method definition cannot be obtained */
Jstring MSG = (* env)-> callvoidmethod (ENV, OBJ, mid );
/* An illegalaccessexception exception will be thrown after this method is called */
Excp = (* env)-> predictionoccurred (ENV );
If (excp ){
(* Env)-> predictionclear (ENV );
// Obtain the exception information by accessing excp
/*
In Java, most of the exception information is extended class java. Lang. exception, so you can access the tostring of excp.
Or getmessage to get the exception information. The methods for accessing these two methods are the same as those for how to restore the class.
*/
}
  
  
Thread and synchronous access
In some cases, you need to use multiple threads to access Java. We know that a Java Virtual Machine consumes a lot of system memory resources, and each virtual machine requires about 20 mb of memory. To save resources, each thread must use the same virtual machine. In this way, only one virtual machine needs to be initialized in the entire JNI program. This is what everyone thinks. But once the sub-thread accesses the virtual machine environment variable created by the main thread, the system displays an error dialog box and the entire program is terminated.

In fact, this involves two concepts: Virtual Machine (JavaVM * JVM) and virtual machine environment (jnienv * env ). JVM rather than env is the one that actually consumes a lot of system resources. JVM promises to access multiple threads, but env can only be accessed by the thread that creates it, in addition, each thread must create its own virtual machine environment Env. At this time, some people may ask, the main thread creates the virtual machine environment env when initializing the virtual machine. To allow the subthread to create its own ENV, JNI provides two functions: attachcurrentthread and detachcurrentthread. The following code is the framework of the sub-thread to access the Java method:

DWORD winapi threadproc (pvoid dwparam)
{
JavaVM JVM = (JavaVM *) dwparam;/* pass in VM parameters */
Jnienv * env;
(* JVM)-> attachcurrentthread (JVM, (void **) & ENV, null );
.........
(* JVM)-> detachcurrentthread (JVM );
}
Time
The topic about time is a problem I encountered in actual development. To release a program that uses JNI, you are not required to install a Java Runtime Environment, because you can package the runtime environment in the installer. To make the package program easier to download, this package should be relatively small, so some unnecessary files in the JRE (Java Runtime Environment) should be removed. However, if the calendar type in Java is used in the program, such as Java. util. calendar, there must be a file that cannot be removed. This file is [JRE] \ Lib \ tzmappings. It is a time zone ing file. Without this file, you will find that the time operation often differs from the correct time by several hours. The following is a list of essential files in JRE packaging (taking windows as an example). [JRE] is the directory of the running environment, and the relative paths between these files cannot be changed.

File Name directory HPI. DLL [JRE] \ bin ioser12.dll [JRE] \ bin Java. DLL [JRE] \ bin net. DLL [JRE] \ bin verify. DLL [JRE] \ bin zip. DLL [JRE] \ bin JVM. DLL [JRE] \ bin \ classic RT. jar [JRE] \ Lib tzmappings [JRE] \ Lib
Since Rt. jar is about 10 MB, but a large part of the files are not required, you can delete them according to the actual application. For example, if the program does not use Java swing, you can delete all files involved in swing and repackage them. (Dynasty network wangchao.net.cn)

Related Article

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.