Step by step teach you to call C ++ in JAVA

Source: Internet
Author: User

1. Introduction to JNI
  
JNI: Java Native Interface is a common Interface provided by the Java language for interaction between Java code and localized code. Localized Code refers to machine-related Binary Code directly compiled, rather than intermediate code such as Java bytecode. In Windows, executable files, DLL files, and SO files in Linux are binary code.
  JNI allows Java programs to interoperate with libraries (DLL, SO) or executable files written in other languages, including assembly, C, and C ++. JNI has the following requirements:
  (1) Your application needs to use system-related functions, but Java code does not support or is difficult to do. This is a typical Implementation of the tray icon, there are several ready-made solutions are made using JNI, the name seems to be called TrayIcon and StayOnTop. Of course, if Java 1.6 is used, it should be another matter.
  (2) There are class libraries or programs written in other languages, and you want Java programs to use them.
  (3) For higher performance requirements, we hope to use the assembly or C/C ++ language to implement some functions.
  JNI Tutorial:

 

2. Basic Steps for Calling C ++ in JAVA

(1) compile java classes with native Methods
  (2) Use the javac command to compile the compiled java class
  (3) Use the javah command to process class files and generate C/C ++ header files
  (4) use C/C ++ to implement local methods
  (5) generate a dynamic connection library for files written in C/C ++

(6) Place the generated. dll library in the c:/windows/system32 directory.

 

The following describes these steps:

(1) Needless to say, it is to write a method with native in java. For example, private native void sum (int x, int y );

(2) enter the directory where the class is located, compile it with javac, and generate the. class file.

(3) This step is very important. In many cases, the header file of c ++ cannot be generated, and the system always prompts that the corresponding class cannot be found. In this case, you must check the configured environment variables. if the problem persists, run the following command: javah-classpath. jni com. chnic. service. business, this command is generally easy to use.

Com. chnic. service is the package name and business is the class name. The Directory of the test class is: C:/Documents and Settings/Administrator/workspace/jn2/ src/com/chnic/service. In this way, the C ++ header file compiled by you will appear in the src directory.

(4) Open VC ++ 6.0 to create Win32 Dynamic-Link Library. Then copy the header file you just generated to the project directory. For example, if the created working directory is D:/Program Files/Microsoft Visual Studio/MyProjects/FruitFactory. copy h, jni_md.h to this directory, because your C ++ header file contains these two header files. They can be found in the jdk directory, under the C:/Program Files/Java/jdk1.6.0 _ 21/include directory and C:/Program
Files/Java/jdk1.6.0 _ 21/include/win32 Directory. Then you can implement the functions you want in C ++.

(5) Compile, run, and generate a dynamic link library, for example, Business. dll.

(6) then place the dynamic link library under c:/windows/system32. In this way, you can execute functions in C ++ in java.

 

Example:

 

Compile and generate Business. dll to run in JAVA. Java code:

Package com. chnic. service;

Public class Business {
Public Business (){}
Static {
 
System. loadLibrary ("FruitFactory ");
 
 
}
 
Public native double getPrice (String name );
Public native Order getOrder (String name, int amount );
Public native Order getRamdomOrder ();
Public native static void analyzeOrder (Order order );

 
Public void notification (){


System. out. println ("Got a notification ");

}
 
Public static void icationicationbystatic (){

System. out. println ("Got a notification in a static method ");


}
 
 
 
}

Java code:

Package com. chnic. service;

Public class Order {
Private String name = "Fruit ";
Private double price;
Private int amount = 30;
Public String getName (){
Return name;
}
Public void setName (String name ){
This. name = name;
}
Public double getPrice (){
Return price;
}
Public void setPrice (double price ){
This. price = price;
}
Public int getAmount (){
Return amount;
}
Public void setAmount (int amount ){
This. amount = amount;
}

 
 
}

 

C ++ code:

 

# Include <iostream. h>
# Include <string. h>
# Include "com_chnic_service_Business.h"
Jobject getInstance (JNIEnv * env, jclass obj_class );

JNIEXPORT jdouble JNICALL Java_com_chnic_service_Business_getPrice
(JNIEnv * env, jobject obj, jstring name ){
Const char * pname = env-> GetStringUTFChars (name, NULL );
If (strcmp (pname, "Apple") = 0 ){
Env-> releasestringutfchars (name, pname );
Cout <"after release:" <pname <Endl;
Return 1.2;
}

Else {

Env-> releasestringutfchars (name, pname );
Cout <"after release:" <pname <Endl;
Return 2.1;

}

 

}
Jniexport jobject jnicall java_com_chnic_service_business_getorder
(Jnienv * ENV, jobject OBJ, jstring name, jint amount ){

Jclass order_class = env-> findclass ("com/chnic/service/order ");
Jobject order = getinstance (ENV, order_class );
Jmethodid setname_method = env-> getmethodid (order_class, "setname", "(ljava/lang/string;) V ");
Env-> callvoidmethod (Order, setname_method, name );

JmethodID setAmount_method = env-> GetMethodID (order_class, "setAmount", "(I) V ");
Env-> CallVoidMethod (order, setAmount_method, amount );

Return order;

}

 

JNIEXPORT jobject JNICALL Java_com_chnic_service_Business_getRamdomOrder
(JNIEnv * env, jobject obj ){

Jclass business_class = env-> GetObjectClass (obj );
Jobject business_obj = getInstance (env, business_class );

JmethodID notification_method = env-> GetMethodID (business_class, "notification", "() V ");

Env-> CallVoidMethod (business_obj, icationication_method );

 

 

Jclass order_class = env-> FindClass ("com/chnic/service/Order ");

Jobject order = getinstance (ENV, order_class );

Jfieldid amount_field = env-> getfieldid (order_class, "amount", "I ");
Jint amount = env-> getintfield (Order, amount_field );
Cout <"amount:" <amount <Endl;
Return order;

 

 

 

}

 

Jniexport void jnicall java_com_chnic_service_business_analyzeorder
(Jnienv * ENV, jclass CLs, jobject OBJ ){

Jclass order_class = env-> getobjectclass (OBJ );
Jmethodid getname_method = env-> getmethodid (order_class, "getname", "() ljava/lang/string ;");

Jstring name_str = static_cast <jstring> (env-> callobjectmethod (OBJ, getname_method ));

Const char * pname = env-> GetStringUTFChars (name_str, NULL );

Cout <"Name in Java_com_chnic_service_Business_analyzeOrder:" <pname <endl;

JmethodID icationication_method_static = env-> GetStaticMethodID (cls, "icationicationbystatic", "() V ");

Env-> CallStaticVoidMethod (cls, icationication_method_static );

 

}
Jobject getInstance (JNIEnv * env, jclass obj_class)
{
JmethodID construction_id = env-> GetMethodID (obj_class, "<init>", "() V ");

// Obtain the ID of the constructor.
Jobject obj = env-> NewObject (obj_class, construction_id );

// Obtain the object of the corresponding class based on the constructor
Return OBJ;
}

 

 

 

Mainly explain the methods in C ++:

Getstringutfchars: converts string type (jstring) to Char.

Releasestringutfchars: releases string space. Because the memory needs to be allocated during creation, release it.

Findclass: Find the corresponding class object based on the class name. The complete package name + class name is required.

Getobjectclass: the input parameter is an object. Find the corresponding class based on the object.

Getfieldid and getmethodid: Find the ID of the corresponding member variable and member method. Because the value and set value of member variables are divided into two steps, the first step is to obtain the corresponding ID, and the second step is to set the value based on the ID number or value. The input parameters include class, member variable (method name), and variable (method signature ). The signature can be obtained by javap-S Class Name (business.

Get the value of the corresponding variable by getintfield. The input parameter is OBJ and the variable ID.

Getstaticintfield obtains the value of the static variable. The input parameter is class, the ID of the variable.

Setintfield: set the value of the variable.

Setstaticintfield: set the value of the static variable.

 

Getobjectfield, setobjectfield if you want to get the string value, and set the string value. For example:

 

Jfieldid FID; // store the field ID
Jstring jstr;
Const char * str;

Jclass cls = env-> GetObjectClass (obj); // get class
Fid = env-> GetFieldID (cls, "s", "Ljava/lang/String ;");
If (fid = NULL ){
Return;
}

Jstr = (jstring) (env-> GetObjectField (obj, fid); // It is divided into two steps. The first step is field.
// Id. The field value can be obtained in step 2.
Str = env-> GetStringUTFChars (jstr, NULL); // convert to char type

If (str = NULL ){
Return;
}
Cout <"In C:" <endl;
Cout <"c. s =" <str <endl;

// Create a string and assign it to field
Jstr = env-> NewStringUTF ("123 ");
If (jstr = NULL ){
Return;
}

Env-> SetObjectField (obj, fid, jstr); // assign a value to this field

 

CallVoidMethod: Call a non-static method. The input parameter is obj and the method ID.

CallStaticVoidMethod: Call a static method. The input parameter is class and the ID of the method.

NewStringUTF (string str): used to construct a string object.

 

The basic content of JNI is introduced here.

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.