First, let's take a look at the two functions in our JAVA file. Both functions are very simple. Note that they are static.
package mm.nn.oo; public class CJava { public static String GetStr() { return "THIS STRING IS FROM JAVA!!!"; } public static int Add(int m, int n) { return m + n; } }
Then generate the corresponding. put the CLASS file in the directory mm \ nn \ n \ oo corresponding to the package name, and wait for it to be called by CPP. create a CPP project and add the JNI directory in "property =" configuration property = "VC ++": $ (JAVA_HOME) \ include \ win32 and $ (JAVA_HOME) \ include. add the library directory required to create a java vm in the library Directory: % JAVA_HOME % \ lib. then our CPP Code looks like this:
# Include
# Include
# Pragma comment (lib, "jvm") int main () {JavaVM * pJvm; // Virtual Machine pointer JNIEnv * pEnv; // environment pointer JavaVMInitArgs VM_Args; JavaVMOption Options [3]; VM_Args.version = JNI_VERSION_1_2; // this field must be set to this value Options [0]. optionString = "-Djava. compiler = NONE "; // disable loading Options by JIT compiler [1]. optionString = "-Djava. class. path =. ";//. CLASS File Path Options [2]. optionString = "-verbose: jni"; // The information used for tracking runtime VM_Args.version = JNI_VERSION_1_2; // the version number VM_Arg S. nOptions = 3; VM_Args.options = Options; VM_Args.ignoreUnrecognized = JNI_TRUE; if (JNI_CreateJavaVM (& pJvm, (void **) & pEnv, & VM_Args )! = JNI_ERR) {jclass JCls = pEnv-> FindClass ("mm/nn/oo/CJava"); system ("CLS "); printf ("************************************* * *********** \ n "); if (JCls! = 0) {jmethodID pMID = pEnv-> GetStaticMethodID (JCls, "Add", "(II) I"); if (pMID! = 0) {printf ("% I \ n", pEnv-> CallStaticIntMethod (JCls, pMID, 5, 5);} pMID = pEnv-> GetStaticMethodID (JCls, "GetStr ", "() Ljava/lang/String;"); if (pMID! = 0) {jstring TempStr = (jstring) pEnv-> CallStaticObjectMethod (JCls, pMID); const char * pTemp = pEnv-> GetStringUTFChars (TempStr, 0 ); printf ("% s \ n", pTemp); pEnv-> ReleaseStringUTFChars (TempStr, pTemp);} pEnv-> DeleteLocalRef (JCls);} pJvm-> DestroyJavaVM (); // release Virtual Machine}
Well, it's so simple. The final project download portal attached to this Demo: http://t.cn/8syetyV
I solemnly declare the following: I. This article from the CSDN blog, portal: http://BlOG.CSDN.NET/yirancpp Ii. All Rights Reserved. This statement cannot be removed when any individual or website reposts this article. 3. You are not allowed to modify the document unless explicitly stated. You are also welcome to repost and share your comments.