There is a Jnihelper class in cocos2d-x for detailed use

Source: Internet
Author: User

Main ideas

Get the Java virtual machine through JNI, get the JNI environment of the current program, get the Java class information that needs to be called through the JNI environment, and get the function information in the Java class that needs to be called. The corresponding Java functions are invoked using the class information and function information through the JNI environment.
It seems a bit complicated, but don't worry, there is a Jnihelper class in cocos2d-x (the copyright of the header file is: cocos2d-x.org, it is provided by Google or the Cocos2d-x group of its own package I do not know), It has encapsulated the work.

Use of the Jnihelper class

Add the following header file:

#include "Platform/android/jni/jnihelper.h"

The interface you need to use is as follows:

static bool Getstaticmethodinfo (Jnimethodinfo &methodinfo, const char *classname, const char *methodname, const char * Paramcode); static bool Getmethodinfo (Jnimethodinfo &methodinfo, const char *classname, const char *methodname, const Char *paramcode);

On the implementation we only need to use the above two interfaces, we can get all the functions of the Java class information. The acquisition of the JNI environment and the various error handling are already encapsulated in these two interface implementations.
First the code, then the meaning of each parameter and how to use it:

    function information structure body    jnimethodinfo minfo;    BOOL Ishave = Jnihelper::getstaticmethodinfo (reference to Minfo,/*jnimethodinfo */                                                 "Com/omega/myapp",/* Path of Class */                                                 " Getjavaactivity ",/* Function name *                                                 /" () Ljava/lang/object; "); * Function Type Shorthand */    jobject activityobj;    if (Ishave)    {        //callstaticobjectmethod calls the Java function and assigns the return value to activityobj        activityobj = minfo.env-> Callstaticobjectmethod (Minfo.classid, Minfo.methodid);    }

OK, very simple. The code above is a typical use of a Java class static function called in C + + using JNI. There are only two steps:

    • 1. Get information about Java functions, ClassID, Methodid, etc.
    • 2. Select an interface in the jnienv to make a function call
Getstaticmethodinfo parameter explanation

Two interface parameters, the same meaning is the same, explained below:
Jnimethodinfo a reference to the &methodinfo Jnimethodinfo object, the JNIEVN, ClassID, and Methodid are written to the reference in the function execution.
const char *classname the path to the class, write the full package name of the class, and use the code as above.
The const char *methodname function name, the function name is written on the line.

const char *paramcode function type shorthand
This parameter needs to be described separately, in the form of: (parameter) return type.
For example: no parameter, void return type function, abbreviated as () V
The types in Java correspond to the following abbreviations:

parameter Type parameter Shorthand
Boolean Z
Byte B
Char C
Short S
Int I
Long J
Float F
Double D
void V
Object ljava/lang/string; L use/split the full path of the class
Array [Ljava/lang/string; [Signature [I

Functions with multiple parameters
If the function has more than one parameter, simply parallel the shorthand. Note the semicolon at the end of the object with the array type parameter shorthand, example:
IIII//4 functions of int type parameter
Iljava/lang/string;i//shaping, String type, shaping combination (int x, string a, int y)

function calls via JNIEnv

JNIEVN has a series of callstatic[return type]method, call[return type]method interfaces that need to be called for different function return type selection.
[Return type] is different from the function return type, corresponding to a different function name.
For example:
Callstaticvoidmethod ——— Void
Callvoidmethod ——— Void
The corresponding relationship is as follows:

Name of function function return value type
Void void
Object Jobject
Boolean Jboolean
Byte Jbyte
Char Jchar
Short Jshort
Int Jint
Long Jlong
Float Jfloat
Double Jdouble

Parameter passing
When invoking a Java function with parameters, the corresponding arguments need to be passed in. Parameters need to be added sequentially to ClassID, Methodid, and type conversions are required. For example:

Jint JX = 10;jint JY = 10;minfo.env->callstaticvoidmethod (Minfo.classid, Minfo.methodid, JX, JY);

The parameter type conversion relationship is as follows:

C + + types Java Type
Boolean Jboolean
Byte Jbyte
Char Jchar
Short Jshort
Int Jint
Long Jlong
Float Jfloat
Double Jdouble
Object Jobject
Class Jclass
String Jstring
Object[] Jobjectarray
Boolean[] Jbooleanarray
Byte[] Jbytearray
Char[] Jchararray
Short[] Jshortarray
Int[] Jintarray
Long[] Jlongarray
Float[] Jfloatarray
Double[] Jdoublearray

Conversion of String type
In fact, our most commonly used parameter types are mainly built-in data types, string string types. The data type can be converted directly to type J, but the string type needs to be handled as follows:

Jstring jmsg = Minfo.env->newstringutf ("http://www.baidu.com"); Minfo.env->callstaticvoidmethod ( Minfo.classid, Minfo.methodid, jmsg);
Calls to non-static functions

A call to a non-static function is a call type of a static function, but a Java class object needs to be obtained through a static function.
Example:

//c++ code//1. Get activity static object Jnimethodinfo Minfo;                                                 BOOL Ishave = Jnihelper::getstaticmethodinfo (Minfo, "Com/omega/myapp", "Getjavaactivity", "() ljava/l    Ang/object; ");    Jobject activityobj;        if (ishave) {//calls the static function getjavaactivity, gets the Java class object.    Activityobj = Minfo.env->callstaticobjectmethod (Minfo.classid, Minfo.methodid); }//2. Find the Displaywebview interface, get its function information, and call Ishave with jobj = Jnihelper::getmethodinfo (Minfo, "Com/omega/myapp", "Displaywebview", "(     IIII) V ");    if (!ishave) {cclog ("Jni:displaywebview function does not exist");        } else {//call this function jint JX = (int) TlX;        Jint JY = (int) TlY;        Jint jwidth = (int) webwidth;        Jint jheight = (int) webheight;    Call the Displaywebview function and pass in the parameter Minfo.env->callvoidmethod (activityobj, Minfo.methodid, JX, JY, Jwidth, jheight); }
Detailed Sample Code

Finally, put a more detailed JNI usage code, basically covering all the usage.

    Jnimethodinfo minfo;//jnihelper/* Test method *//*bool Ishave = Jnihelper::getstaticmethodinfo (Minfo, "com/cocoa/ Hiworld "," Logingree "," () V ");     if (ishave) {//cclog ("with Showtext");     Minfo.env, Callstaticvoidmethod (Minfo.classid,minfo.methodid);     }else {//cclog ("no Method Showtext");     }*//* Share *//*//Convert a string in C + + to string//char str[] = "Test" in Java; BOOL Ishave = Jnihelper::getstaticmethodinfo (Minfo, "Com/cocoa/hiworld", "Sharesina", "(ljava/lang/string; ljava/lang/string;) V ");     if (ishave) {//cclog ("with share");     Jstring jstr = Minfo.env->newstringutf ("Test1 share");      jstring JST = Minfo.env->newstringutf ("/data/data/com.cocoa/cy.png");     jstring JST = Minfo.env->newstringutf ("");     Minfo.env, Callstaticvoidmethod (MINFO.CLASSID,MINFO.METHODID,JSTR,JST);     }else {//cclog ("no Method share");     }*//* Set high Score *//*jint ind = 0;     Jlong lsre = 2202l; BOOL Ishave = Jnihelper::getstaticmethodInfo (Minfo, "Com/cocoa/hiworld", "Sethighscore", "(IJ) V");                 if (ishave) {minfo.env, Callstaticvoidmethod (MINFO.CLASSID,MINFO.METHODID,IND,LSRE);     }*//* Achievement unlocking *//*jint aind = 0;      BOOL Ishave = Jnihelper::getstaticmethodinfo (Minfo, "Com/cocoa/hiworld", "UnLock", "(I) V");                 if (ishave) {minfo.env, Callstaticvoidmethod (Minfo.classid,minfo.methodid,aind); }*//* Test method */bool Ishave = Jnihelper::getstaticmethodinfo (Minfo, "Com/cocoa/hiworld", "Rtnactivity", "() ljava/lang/    Object; ");    Jobject jobj;     if (ishave) {jobj = Minfo.env->callstaticobjectmethod (Minfo.classid, Minfo.methodid);     }//cclog ("jobj exists");      /* Test method, non-static no parameter no return value method *//*ishave = Jnihelper::getmethodinfo (Minfo, "Com/cocoa/hiworld", "Showtext", "() V");     if (ishave) {minfo.env, Callvoidmethod (Jobj,minfo.methodid); }*//* Test method, non-static string parameter with Java type no return value method *//*ishave = Jnihelper::getmethodinfo (Minfo, "com/cocoa/hIworld "," Showtext "," (ljava/lang/string;) V ");     if (ishave) {jstring jmsg = Minfo.env->newstringutf ("msg okey!");     Minfo.env, Callvoidmethod (jobj,minfo.methodid,jmsg); }*//* Test method, return Java type string, Java type string and int parameter method *//*ishave = Jnihelper::getmethodinfo (Minfo, "Com/cocoa/hiworld"      , "Showtext", "(ljava/lang/string;i) ljava/lang/string;"); if (ishave) {jstring jmsg = Minfo.env->newstringutf ("msg okey!     return string ");     Jint index = 0;     Minfo.env, Callobjectmethod (Jobj,minfo.methodid,jmsg,index); }*//* Test method, return Java type string[], have Java type string[] and int parameter method *//*ishave = Jnihelper::getmethodinfo (Minfo, "Com/cocoa/hiwo      Rld "," Showtext "," ([ljava/lang/string;i) [ljava/lang/string; ");     if (ishave) {Jobjectarray args = 0;     Jstring str;     Jsize len = 5;     Const char* sa[] = {"Hi,", "world!", "JNI", "is", "Fun"};     int i = 0;     args = Minfo.env->newobjectarray (Len,minfo.env->findclass ("java/lang/string"), 0); for (i=0;inewstringutf (Sa[i]);     Minfo.env->setobjectarrayelement (ARGS,I,STR);     }//minfo.env->getstringarrayregion (ARGS,0,10,BUF);     Jintarray jmsg = {n/a}; Minfo.env->newstringutf ("Msg okey!     return string ");     Jint index = 0;     Minfo.env, Callobjectmethod (Jobj,minfo.methodid,args,index);  }*/*/* test method, no return type, Java type int[] and int parameter method *//*ishave = Jnihelper::getmethodinfo (Minfo, "Com/cocoa/hiworld", "Testarr",      "([II) V");     if (ishave) {Jint buf[]={7,5,8,9,3}; Jintarray Jintarr;     Defines the jint array Jintarr = Minfo.env->newintarray (5);     Minfo.env->setintarrayregion (JINTARR,0,5,BUF);     Jint index = 0;     Minfo.env, Callvoidmethod (Jobj,minfo.methodid,jintarr,index); }*/*/* test method, no return type, Java type byte[] and int parameter method */Ishave = Jnihelper::getmethodinfo (Minfo, "Com/cocoa/hiworld", "Testarr",     "([BI) V");        if (ishave) {Jbyte buf[]={7,5,8,9,3}; Jbytearray Jbytearr; Define Jbyte Array Jbytearr = Minfo.env->newbytearRay (5);        Minfo.env->setbytearrayregion (JBYTEARR,0,5,BUF);        Jint index = 0;    Minfo.env, Callvoidmethod (Jobj,minfo.methodid,jbytearr,index); }
private static Hiworld Hiworld = null;protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstance    State);    Hiworld = this; if (detectOpenGLES20 ()) {//Get the Packagename,it ' s used to set the resource path String PackageName = Get        Application (). Getpackagename ();        Super.setpackagename (PackageName);        Set content Setcontentview (R.layout.game_demo);        GetWindow (). Setfeatureint (Window.feature_custom_title, r.layout.window_title);        Mglview = (Cocos2dxglsurfaceview) Findviewbyid (R.id.game_gl_surfaceview);        Mglview.settextfield ((Cocos2dxedittext) Findviewbyid (R.id.textfield));        Mglview.seteglcontextclientversion (2);        Mglview.setcocos2dxrenderer (New Cocos2dxrenderer ());                task = new TimerTask () {@Override public void run () {//Hiworld.shoot (Hiworld);          LOG.E ("-------------------", "-------------------");      Call method System.out.println in C + + ("------------------------" + string            Zjy1 ());        }        };        Timer = new timer ();    Timer.schedule (task, 5000);        } else {log.d ("activity", "Don t support gles2.0");    Finish ();    } static {System.loadlibrary ("game");        }//C + + method public static Object rtnactivity () {System.out.println ("----------rtnactivity");    return hiworld;  }//C + + method, pass String type public void Showtext (Final String msg) {//Add to main thread Hiworld.runonuithread (new            Runnable () {public void run () {System.out.println ("----------msg:" +msg);    }        }); }//c++ method, String type and int type public string Showtext (final String msg,final int index) {//Add to main thread hi World.runonuithread (New Runnable () {public void run () {System.out.println ("----------msg:" +ms G+ "; index= "+index);        }        });    Return "Okey string Showtext (final string msg,final int index)"; }//c++ method, string[] type and int type public string[] Showtext (final string[] msg,final int index) {string[] Stra        rr = {"1", "2", "3", "4", "5"}; Add to main thread Hiworld.runonuithread (new Runnable () {public void run () {for (String _str:msg {System.out.println ("----------string[] msg:" +_str+ ";                index= "+index);        }            }        });    return strarr; }//c++ method, pass int[] type and int type public void Testarr (final int msg[],final int index) {//Add to main thread Hiworld . Runonuithread (New Runnable () {public void run () {System.out.println ("----------int[] msg len                : "+msg.length); for (int _bl:msg) {System.out.println ("----------int[] msg:" +_bl+ ";                index= "+index);    }            }        }); }//c++ method, pass int[] type and int type publIC void Testarr (final byte msg[],final int index) {//Add to main thread Hiworld.runonuithread (new Runnable () {                public void Run () {System.out.println ("----------byte[] msg len:" +msg.length); for (int _bl:msg) {System.out.println ("----------byte[] msg:" +_bl+ ";                index= "+index);    }            }        }); }

Cocos2d-x has a jnihelper class that is used in detail

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.