COCOS2D-X3.3RC0 implementing Java and C + + intermodulation via JNI

Source: Internet
Author: User

First, JNI
JNI (Java Native Interface): Native invocation of Java. This paper accomplishes the intermodulation of Java and C + + through JNI in COCOS2D-X3.3RC0. The following two functions are implemented specifically
can: (1) Get the package name of the application through the API of the Android SDK and pass it to the C + + layer function. (2) Call the Java layer function of Android via C + + function, display a dialog box. Click the button to exit the program.
For
more information, see http://blog.csdn.net/yuxikuo_1/article/details/39577257. One of the most important is jnienv, which is a C struct. Encapsulates a number of
common functions: Specific as follows:
struct _JNIENV {    /* don't rename this; it does not seem to be entirely opaque */    const str UCT jninativeinterface* functions;  #if defined (__cplusplus)      jint GetVersion ()     {return functions->getversion (this);}      jclass defineclass (const char *name, Jobject loader, const jbyte* buf,         jsize buflen)     {return Functions->defineclass (this, name, Loader, buf, buflen); }     jclass findclass (const char* name)     {return functions-> Findclass (this, name); }//here omit other functions ...  } 
Cocos2d-x encapsulates the operation of JNI and provides the Jnihelper class to solve the communication between Java and C + +.
here are two common functions:
1.Getstaticmethodinfo:

        Used to determine whether a static function exists in a Java class and initializes the struct jnimethodinfo. The structure encapsulates the jnienv* and java.lang.Class, and the function ID. This allows you to call Callstaticxxxmethod (Jclass clazz,jmethodid methodid, ...) using jnienv*. and Callxxxmethod (Jobject obj,jmethodid methodid, ...) such as common functions, where xxx represents a function return value type, such as void, int, and so on. The following code: Parameter 1:jnimethodinfo, parameter 2: The absolute path of the class, The path is: proj.android/src/under the directory, for example, the path under the engine template project is: src/org /cocos2dx/cpp/xxx. XXX is the Java file under CPP. Remember that the path does not add the. java suffix, because the path uses the class name. Parameter 3: function name, Parameter 4: function signature, see 3 type signature

Jnimethodinfo info;  BOOL ret = Jnihelper::getstaticmethodinfo (info, "org/cocos2dx/cpp/appactivity", "Getobj", "() ljava/lang/object;");  Jobject jobj;  if (ret)  {      log ("call void Getobj () succeed");      Jobj = Info.env->callstaticobjectmethod (Info.classid,info.methodid);  }    bool Re = Jnihelper::getmethodinfo (info, "org/cocos2dx/cpp/appactivity", "Func1", "() V");  if (re)  {      log ("Call func1 succeed");      Info.env->callvoidmethod (Jobj,info.methodid);  }  
2. Getmethodinfo: Non-static function for calling Java class
#if (Cc_target_platform = = cc_platform_android)      jnimethodinfo info;      Determine if there is a getobj static function in Org/cocos2dx/cpp/appactivity.java      bool ret = jnihelper::getstaticmethodinfo (info, "org/ Cocos2dx/cpp/appactivity "," Getobj "," () ljava/lang/object; ");      Jobject jobj;//is used to store the returned object      if (ret)      {          log ("call void Getobj () succeed");          Jobj = Info.env->callstaticobjectmethod (Info.classid,info.methodid);//Call getobj function, return an object      }      //judgment org/ Whether there is func1 non-static function      bool re = Jnihelper::getmethodinfo (info, "org/cocos2dx/cpp/" in Cocos2dx/cpp/appactivity.java) Appactivity "," Func1 "," () V ");      if (re)      {          log ("Call func1 succeed");          Info.env->callvoidmethod (Jobj,info.methodid);//call non-static function by the returned object      }        #endif  

3. Type signature
Type signature Java type
Z Boolean
B Byte
C Char
S Short
I Int
J Long
F Float
D Double
L Full-qualified-class; Fully-qualified classes
[Type Type[]
(arg-types) Ret-type Method type

such as the Java method: Long f (int n,string s,int[] arr); Type signature: (iljava/lang/string;[ I) J. Note the semicolon after L, [is semi-open, to be exactly the same as the type signature . Ii. Concrete Step 1, create COCOS2D-X3.3RC0 project
this does not do too much introduction, since the study to JNI, compared to is not too rookie.
2. ADT and Xcode are respectively imported into the project3. Add Jnitest class under the class directory of Xcode
The JniTest.h code is as follows: JniTest.cpp temporarily no code
#ifndef __jnidemo__jnitest__#define __jnidemo__jnitest__#include "Cocos2d.h" using_ns_cc;void setpackagename (const char* PackageName)//The package name sent from the Java layer is printed here {    log ("PackageName =%s", packagename);} void Exitapp ()//java layer calls this function of the C + + layer to close the program. {    director::getinstance ()->end ();}

then include the following header file in the HelloWorldScene.cpp, and add the following code to the Menuclosecallback:
Header file contains, judging platform # if (Cc_target_platform = = cc_platform_android) #include ". /proj.android/jni/hellocpp/test.h "//Must be relative path #endif//call C + + call Java layer code void Helloworld::menuclosecallback (ref* psender {#if (Cc_target_platform = = cc_platform_android)    showtipdialog ("Exit", "exit,really Go?"); #endif    #if (cc_target_platform = = Cc_platform_ios)    exit (0); #endif}
4. JNI Layer Code
Open the jni/hellocpp/list under the ADT project directory and add C + + classes, test.cpp, and Test.h under Hellocpp. The code is as follows: Must contain extern "C"
Test.h#ifndef test_h_#define Test_h_extern "C" {void Showtipdialog (const char* title,const char* msg); #endif
The Test.cpp code is as follows:
Test.cpp#include "Test.h" #include "cocos2d.h" #include "platform/android/jni/jnihelper.h"//engine-supplied Jnihelper class # Include ". /.. /.. /classes/jnitest.h "//relative path, the class created in Xcode in the previous step # include <jni.h> #define CLASS_NAME" Org/cocos2dx/cpp/jnitesthelper " The path to this step is the path to the upper red line, which is important using namespace Cocos2d;extern "C" {<span style= "White-space:pre" ></span><span style= "COLOR: #cc0000;" >//The following function calls the Java layer function through JNI. </span>void showtipdialog (const char* title,const char* msg)//This function is called in Helloworldscene, this function is passed through JNI to the Java layer {< The span style= "White-space:pre" ></span>//calls the Showtipdialog function in the Java layer Jnitesthelper.java jnimethodinfo t;if ( Jnihelper::getstaticmethodinfo (T,class_name, "Showtipdialog", "(ljava/lang/string; Ljava/lang/string, V "))//The function means to look for a org/cocos2dx/cpp/jnitesthelper class with no static function Showtipdialog,<span style=" color:# cc0000; " > haven't released Jnitesthelper code yet, later. </span>{jstring jtitle = T.env->newstringutf (title); Jstring jmsg = T.env->newstringutf (msg);t.env-> Callstaticvoidmethod (T.classid,T.METHODID,JTITLE,JMSG); T.env->deletelocalref (Jtitle); T.env->deletelocalref (JMSG);}} <span style= "color: #cc0000;" >//The following two functions are defined in jnitesthelper by the two functions of the setpackagename and Exitapp,java layers of the C + + layer via JNI, and the parameters are passed jnienv into </span>void Java _org_cocos2dx_cpp_jnitesthelper_setpackagename (jnienv* env,jobject thiz,jstring packageName) {Const char* PkgName = Env->getstringutfchars (Packagename,null); Setpackagename (pkgname);//c++ Layer Code Env->releasestringutfchars ( Packagename,pkgname);} void Java_org_cocos2dx_cpp_jnitesthelper_exitapp (jnienv* env,jobject thiz) {Exitapp ();//c++ Layer Code}}
5. Java Layer Functions
add Java classes in the directory src/org.cocos2dx.cpp the ADT project directory, Jnitesthelper.java
1) The Jnitesthelper.java code is as follows:
Package Org.cocos2dx.cpp;import Org.cocos2dx.lib.cocos2dxhandler.dialogmessage;import Android.os.Handler;import Android.os.message;public class Jnitesthelper {private static Handler Mhandler;//java Handler delivery message public static void Init (Handler Handler) {jnitesthelper.mhandler = Handler;} public static native void Setpackagename (String packagename);//declares two static Nativa functions, defined in Test.cpp in Jni, and invokes the corresponding functions of the C + + layer. public static native void Exitapp ();p rivate static void Showtipdialog (final String title,final string text) {Message msg = Mhandler.obtainmessage ();//Accept message Msg.what = appactivity.show_dialog;dialogmessage DM = new Dialogmessage (title, text); /focus is this step, before the tutorial itself set the data structure, while the new version of the Cocos dm.titile = Title;<span style= "White-space:pre" ></span>// The JNI library provides us with a dialogmessage of this data structure class. So do not customize dm.message = Text;msg.obj = Dm;msg.sendtotarget ();}}
2) Appactivity.java Code
Package Org.cocos2dx.cpp;import Org.cocos2dx.lib.cocos2dxactivity;import Org.cocos2dx.lib.Cocos2dxGLSurfaceView; Import Org.cocos2dx.lib.cocos2dxhandler.dialogmessage;import Android.app.alertdialog;import Android.content.dialoginterface;import Android.os.bundle;import Android.os.handler;import android.os.Message; public class Appactivity extends cocos2dxactivity{public static final int show_dialog = 0x0001;protected void OnCreate (Bun Dle savedinstancestate) {super.oncreate (savedinstancestate); Jnitesthelper.init (Mhandler);//The Handler object in Jnitesthelper is initialized with the handler object defined below. Jnitesthelper.setpackagename (This.getpackagename ());} Public Cocos2dxglsurfaceview Oncreateview () {Cocos2dxglsurfaceview Glsurfaceview = new Cocos2dxglsurfaceview (this); Glsurfaceview.seteglconfigchooser (5,6,5,0,16,8); return glsurfaceview;} static {system.loadlibrary ("Cocos2dcpp");} Private Handler Mhandler = new Handler () {public void Handlemessage (Message msg) {switch (msg.what) {case show_dialog://set up Show box dialogmessage DM = (dialogmesSage) msg.obj;new Alertdialog.builder (appactivity.this). Settitle (Dm.titile). Setmessage (Dm.message). Setnegativebutton ("Cancle", new Dialoginterface.onclicklistener () {@Overridepublic void OnClick (Dialoginterface arg0 , int arg1) {//TODO auto-generated method Stubarg0.dismiss ();}}). Setpositivebutton ("OK", new Dialoginterface.onclicklistener () {public void OnClick (dialoginterface arg0, int arg1) { Arg0.dismiss (); Jnitesthelper.exitapp ();}}). Create (). Show (); break;}};}

Well, the code and comments are basically over, and the Android.mk file is required. The code is as follows:
Local_src_files: = hellocpp/main.cpp    hellocpp/test.cpp \/   /Add the newly created Test.cpp class to the Mk file.                   /.. /classes/appdelegate.cpp.                    /.. /classes/helloworldscene.cpp
Previously introduced the Universal MK file generation method, see http://blog.csdn.net/yuxikuo_1/article/details/39552431. In order to reduce the probability of the problem, it is recommended to change the SDK version in Androidmanifest, do not change the matter.
6. General Engineering Catalogue

third, compile and run
If you have problems, refer to 1) http://blog.csdn.net/yuxikuo_1/article/details/39654499 2)/HTTP// blog.csdn.net/yuxikuo_1/article/details/39552639 3) http://blog.csdn.net/yuxikuo_1/article/details/ 39671733
Note: Environment mac XCode6 ADT22.2.1 cocos2d-x3.3rc0 Red rice note.

Iv. Source Code
said so much, no source that is not the pit father. SOURCE Connection: Http://pan.baidu.com/s/1jGn80QE

COCOS2D-X3.3RC0 implementing Java and C + + intermodulation via JNI

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.