Summary about LUA, C, Android, calling method between Cocos2d-x

Source: Internet
Author: User

Summarize the things you've been doing for a few days.

Environment configuration is also more annoying. Ndk.java. There are configurations in the COCOS2DX environment. Reference 1

Very basic and very basic environment configuration.

between 1.android and C. called

Android uses JNI to invoke C (without C + + play. extern "C"),

1.1android Call C

If you want to compile the Add native support for Android tools in the project, in Eclipse, build C/C + +. The theory of COCOS2DX has been set. Of course, if not. Let's make it up with Cocos compile. If you add a project, you will have a problem with your DARKC. May be the cause of the configuration. Leave a hole ....

  The C method is declared in the COM.EXAMPLE.WIFIIP package Mainactivity.java file under src: Native public void Onbtnclick ();

can choose to use Javah to head C header file compiled, there will be a fixed-format function declaration.

Run->extern Tools

Well, the specific parameters do not work. leave the pit .... JAVAP used for signing Java functions. Used for JNI layer C call java. If you know the rules, you can use them. Mainly to clear descriptor ibid.

1 /*Do not EDIT this file-it are machine generated*/2#include <jni.h>3 /*Header for Class com_example_wifiip_mainactivity*/4 5 #ifndef _included_com_example_wifiip_mainactivity6 #define_included_com_example_wifiip_mainactivity7 #ifdef __cplusplus8 extern "C" {9 #endifTen /* One * class:com_example_wifiip_mainactivity A * Method:onbtnclick - * Signature: () V -  */ theJniexportvoidJnicall Java_com_example_wifiip_mainactivity_onbtnclick -(JNIENV *, jobject); -  - #ifdef __cplusplus + } - #endif + #endif

The function is a rule. Against the above Java file, if you know the rules can not be generated. Write a definition directly

Complete the implementation code in the CPP file.

The Android.mk file is loaded with the relevant compiled and header files and the corresponding instructions. Reference 2

Then compile and run on the line. In the Java code to invoke the

  

       Static {            system.loadlibrary ("WIFIIP");        }

Always forget ....

Actually, it's not too hard.

1.2 C Call Java

Just add the appropriate code to the JNI layer's C + + code.

Calling a static function

    //gets the Mainactivity class, not the object that the object already has: ObjactivityJclass clsactivity = Pjnienv->findclass ("com/example/wifiip/mainactivity"); ///Gets the function ID of the function getwifiaddress in the class, and the third parameter fills in the function's signatureJmethodid method = Pjnienv->getmethodid (Clsactivity,"getwifiaddress","() I"); ///calling Java layer functionsJobjectObject= pjnienv->Newlocalref (Pjobject); intNIp = Pjnienv->callintmethod (Object, method);

Non-static functions

  

    Longstatus;       Jclass CLS;       Jmethodid mid;       Jint Square;       Jboolean not;  Jobject jobj; CLS= (*env)->findclass (env,"Com/example/hellojni/hellojni"); if(CLS! =0) {Jmethodid construction_id= (*env)->getmethodid (env, CLS,"<init>","() V"); if(construction_id = =0) {__android_log_print (Android_log_info,"Pvvvvvv_printstringjni","Result of construction_id== 0"); } jobject Mtestprovider= (*env)NewObject (env, CLS, construction_id);Mid = (*env)->getmethodid (env, CLS,"Dologin","(ZZ) I"); if(Mid! =0) {Square= (*env)Callintmethod (env, Mtestprovider, Mid, Jni_true, jni_true); __android_log_print (Android_log_info,"Pvvvvvv_printstringjni","Dologin%d", Square); }    }

One problem here is to be careful when invoking an interface thread in Android. In the related function of the call context context, this parameter can not be passed this. This place pits me for a long time. Because you're actually in here. Not in a thread. It's empty, I don't know who you are. This yarn. Write a static save this to or pass in all can.

Examples of experiments are: Hellojni.

Call between 2.lua and C

Reference 3. Written in very detailed. I'll simply write it down. Reference 4

C and Lua use stacks to interact. It is also realized in pure C environment. are based on the Cocos. You don't have to do your own environment--!

In the Cocos Environment, LUA calls C to register the C function into Lua.

Auto engine =luaengine::getinstance (); Scriptenginemanager::getinstance ()-Setscriptengine (engine); Luastack* Stack = engine->getluastack (); Stack->setxxteakeyandsign ("2dxLua", strlen ("2dxLua"),"Xxtea", strlen ("Xxtea")); Lua_state*l = stack->getluastate (); Lua_register (L,"Test_lua_bind", Test_lua_bind);

  

You can also get the current Luaengine object from scratch using the Scriptenginemanager class, and then Getluastack () method to get the encapsulated Luastack object, and then call Getluastate () for the original Lua_ The state structure pointer. As long as you know the entrance location, everything else is not a problem, or quite simple.

If you are interested, you can take a look at the detailed definition of the Scriptenginemanager class in the Frameworks/cocos2d-x/cocos/base/ccscriptsupport.h file.

This is directly registered as a global function, actually in the dark project is registered in the namespace. See the project in detail ....

2.2 C + + calls Lua

lua_state* PL =Lua_open ();        Luaopen_base (PL); /*Execute Script*/lual_dofile (PL,"Hellolua.lua"); /*Put the Helloadd function object on the stack*/Lua_getglobal (PL,"Helloadd"); /*put the parameters required by the function into the stack*/Lua_pushnumber (PL,Ten); Lua_pushnumber (PL,5); /*execution function, the first parameter represents the number of arguments to the function, the second parameter represents the number of function return values, LUA first goes to the stack to take out the parameters, then takes out the function object, starts executing the function*/Lua_call (PL,2,1); intIresult = Lua_tonumber (PL,-1);

is still the way to leverage stacks.

It's a lot easier in the Cocos environment.

Write a global approach.

Auto Luastack = Cocos2d::luaengine::getinstance ()Getluastack (); Lua_state* L = luastack->getluastate (); Lua_getglobal (L,"Onsdkinitcallback");/*query function by name, Stack:function*/    if(!lua_isfunction (L,-1) {Cclog ("[Lua ERROR] name '%s ' does not represent a LUA function","Onsdkinitcallback"); Lua_pop (L,1); return; } luastack->executefunction (0);

  

A call between 3.android and Lua.

Originally understood that LUA needed to be tuned first

  Static  Public voidShowalertdialog (FinalString title,FinalString message,Final intluacallbackfunction) {S_instance.runonuithread (NewRunnable () {@Override Public voidrun () {Dosdklogin (false,true); Alertdialog Alertdialog=NewAlertdialog.builder (s_instance). Create ();                Alertdialog.settitle (title);                Alertdialog.setmessage (message); Alertdialog.setbutton ("OK",NewDialoginterface.onclicklistener () {@Override Public voidOnClick (Dialoginterface Dialog,intwhich) {S_instance.runonglthread (NewRunnable () {@Override Public voidrun () {cocos2dxluajavabridge.callluafunctionwithstring (luacallbackfunction,"Xxxclickedvvvxxx");                            Cocos2dxluajavabridge.releaseluafunction (luacallbackfunction);                    }                        });                }                });                Alertdialog.seticon (R.drawable.icon);            Alertdialog.show ();    }        }); }

Using C. Re-invoking Java via JNI in fact, this thing has been integrated under Cocos. Luaj directly to use. Think about all the tears ....

Note the GL thread. And the use of the UI thread

  

4.cocos2d-x 3.0 under Bind Lua

Binding class in the parameter 3 written in very detailed ....  There's really nothing to summarize. The actual item is just the registration function into the implementation. A few 818 see if they have their own registered in the class.

Reference

1. http://jingyan.baidu.com/article/3ea51489e7a9bd52e61bbac7.html

2. http://blog.csdn.net/yili_xie/article/details/4906865

3. http://cn.cocos2d-x.org/tutorial/show?id=1295

4. http://blog.csdn.net/musicvs/article/details/8440707

5. http://blog.csdn.net/xdw1985829/article/details/6900155

Summary about LUA, C, Android, calling method between 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.