Call Java in C/C ++
In this article
Java variables and methods are called in/C ++. The example used in this article is to undertake the JNI Learning Series in the previous article-Calling C/C ++ in Java. Let's take a look at the specific example below.
1
.Slightly modify testnative. Java in the previous article. The bold part of the code below is the modified part.
Testnative. Java
Package com. Yin. JNI; public class testnative {Int number = 10;// The native keyword declares the localization method. You do not need to use Java code to implement public native void sayhello ();Public void function () {system. Out. println ("Hello Java! ");}Public static void main (string [] ARGs) {// load the generated nativecode. DLL file system. loadlibrary ("nativecode"); testnative Tn = new testnative (); // call the sayhello method tn. sayhello (); system. out. println (TN. number );}}
2. Add the new code in the previous jniexport void jnicall java_com_yin_jni_testnative_sayhello (jnienv * ENV, jobject OBJ) method.
Source. cpp
# Include <iostream> # include "com_yin_jni_testnative.h" using namespace STD; jniexport void jnicall encode (jnienv * ENV, jobject OBJ) {// cout <"hello, my first JNI program "<Endl; // get the Class Object jclass clazz = env-> getobjectclass (OBJ) through the OBJ passed in jnit; // use the variable name in class and Java, variable type. Get the required variable jfieldid id_number = env-> getfieldid (clazz, "Number", "I"); // obtain the value of this variable, that is, testnative. value of number in Java jint number = env-> getintfield (OBJ, id_number); // output number cout <number <Endl; // re-assign a value for number // note that the first parameter is 100l, which is a long type, because the int type of Java in JNI corresponds to the long type in C/C ++, for details, refer to the previous article env-> setintfield (OBJ, id_number, 100l); // use env-> getmethodid to obtain the Function Method in Java; // The first parameter is a class object, the third parameter is the target function name, and the third parameter is the method signature. For details, see jmethodid function_id = env-> getmethodid (clazz, "function", "() V") in the previous article "); // call the function method env-> callvoidmethod (OBJ, function_id) in Java );}
Compile and run the above project.
Running result:
10
Hello Java!
100
10 is the count <number <Endl output in C ++;
Note: The Java code does not call the method function, so this method is called in C ++;
The value of number is initially 10 through env-> setintfield (OBJ, id_number, 100l) in C ++; changed to 100;
The above is a simple call to Java in C/C ++. If you are familiar with the reflection in Java, you will be familiar with the above method. It looks like reflection.
Many methods have been defined in the header file of JNI. H. You can study these methods on your own ....