Calling Java methods using JNI in Cocos2d-x

Source: Internet
Author: User

When publishing Android projects with Cocos2d-x. Should know that it involves JNI operations (Java Native Interface) in order to interact with C + + in Java. JNI is a common interface for Java. Designed to localize languages, such as c\c++, to interact with the Java language. In the interactive process, Java calls the binary code of the compiled localized language, such as a DLL under Windows. So files under Linux). So when you cross-compile, you see the console output from Eclipse.

[Armeabi] SharedLibrary:libcocos2dcpp.so
[Armeabi] Install:libcocos2dcpp.so = libs/armeabi/libcocos2dcpp.so

It can be thought that the COCOS2D-X project was successfully compiled on the Android platform, and the idea was to generate the binary file (Dynamic Connection library) to interact with the native language of Android ——— Java, and the process of interaction required an intermediate bridge. This bridge is JNI.

Then the next note is how to use JNI in C + + to invoke member methods or static methods in the Java language with Cocos2d-x.

In Cocos2d-x, there is a packaged class--jnihelper for easy operation of JNI, and the following two functions are used to obtain the Java class information.

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);
As the name implies, the first function is to get information about a static method. The second is the information that gets the member method. The parameters are consistent.

Reference to the Methodinfo:jnimethodinfo class

ClassName: The path of the class (that is, the package name plus the class name)

MethodName: Method Name

Paramcode: Method's parameter type and return value type

The rules for writing the fourth of these parameters are as follows:

(parameter type ...) Returns a value type.

Write rules to take the official documents of Oracle Http://docs.oracle.com/javase/7/docs/technotes/guides/jni/spec/types.html

When a C + + data type is mapped to a Java data type, it is defined by one of the following federation methods

typedef Union JVALUE {     Jboolean z;     Jbyte    B;     Jchar    C;     Jshort   S;     Jint     i;     Jlong    J;     Jfloat   F;     Jdouble  D;     Jobject  

Can see. This union includes the 8 OST data types that map Java and one of its own definition types. This includes the mapping of all Java data types.

And. The Java VM (Java Virtual machine) also defines a signature to indicate the data type of Java

Z Boolean

B byte

C Char

S shot

I int

J Long

F float

D Double

L Fully-qualified-class; Fully-qualified-class (note semicolon)

[Type type[]

(arg-types) Ret-type method type

To give a sample,

Suppose you want to call a Java method

Long f (int n, String s, int[] arr);

Then the fourth parameter (Paramcode) can be written as

(iljava/lang/string; [I) J

Of course, the above naming conventions can also be obtained through Java decompile.

watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqva2luz2fiy2rl/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma==/ Dissolve/70/gravity/center ">

You can see all the method signatures for a class. It also explains that the Java virtual machine is using the method signature above to find the corresponding method entry address when parsing Java bytecode.

Next, we'll test the process of using Jnihelper to help implement C + + calling a static Java method with a parameter and a return value.

1. Create a new Cocos2d-x project. Then get eclipse to compile. Edit the entry class after compiling, add the Java code we want to test

Package Com.cocos2dx.testjni;import Org.cocos2dx.lib.cocos2dxactivity;import Org.cocos2dx.lib.cocos2dxglsurfaceview;import Android.os.bundle;public class Testjni extends Cocos2dxActivity{    protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);}    Public Cocos2dxglsurfaceview Oncreateview () {    Cocos2dxglsurfaceview Glsurfaceview = new Cocos2dxglsurfaceview ( this);    Testjni should create stencil buffer    Glsurfaceview.seteglconfigchooser (5, 6, 5, 0, +, 8);        return glsurfaceview;    }    static {        system.loadlibrary ("Cocos2dcpp");    }             Add Java Test Code/////////////////////////public  static string Staticmethod (int i, string STR, double D) {  return "I:" + i + ", str:" + str + ", D:" + D;  }}

2. Change the HelloWorldScene.cpp to increase the JNI calling code

#include "HelloWorldScene.h" #if (cc_target_platform = = cc_platform_android) #include <jni.h> #include "platform/ Android/jni/jnihelper.h "#endifUSING_NS_CC;    ccscene* Helloworld::scene () {Ccscene *scene = Ccscene::create ();    HelloWorld *layer = Helloworld::create ();    Scene->addchild (layer); return scene;} BOOL Helloworld::init () {if (!    Cclayer::init ()) {return false; } #if (Cc_target_platform = = cc_platform_android) Jnimethodinfo methodinfo;//infers whether the method exists bool Isexist = Jnihelper:: Getstaticmethodinfo (MethodInfo, "Com/cocos2dx/testjni/testjni", "Staticmethod", "(iljava/lang/string;d) Ljava/lang /string; ");  if (isexist) {Jint i = 0;jdouble d = 1.22;jstring str = METHODINFO.ENV-&GT;NEWSTRINGUTF ("Test Static Method");//Create jstring S = (jstring) methodinfo.env->callstaticobjectmethod (Methodinfo.classid, Methodinfo.methodid, I, str, d);// Call the Java Method const char* C = methodinfo.env->getstringutfchars (s, 0);//Turn jstring into a character pointer//display the returned string in the screen cclabelttf* TTF = Cclabelttf::create (c, "ARial, Ttf->setposition (CCP), This->addchild (TTF);//Release Memory methodinfo.env-> Releasestringutfchars (S, c); Methodinfo.env->deletelocalref (str);} else {cclog ("share Error");} #endif return true;}

You can see the success of the call by executing the result:

watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqva2luz2fiy2rl/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma==/ Dissolve/70/gravity/center ">

Calling Java methods using JNI in Cocos2d-x

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.