cocos2dx-lua编程之c++与lua通信,c++与java通信

cocos2dx-lua编程之c++与lua通信,c++与java通信,第1张

概述1. MessageCenter.h #ifndef __MESSAGECENTER_H__#define __MESSAGECENTER_H__#include <string>#include <list>struct lua_State;class MessageCenter{public: MessageCenter(void); ~MessageCenter(voi 1.MessageCenter.h


#ifndef __MESSAGECENTER_H__#define __MESSAGECENTER_H__#include <string>#include <List>struct lua_State;class MessageCenter{public:	MessageCenter(voID);	~MessageCenter(voID);	static MessageCenter * getInstance();	static int  lua_bind_AllFunction(lua_State* tolua_S);	voID cppSendMessagetoJava(const std::string & message);	voID addMessagetoList(const std::string &message);	const std::string luaGetMessageFromCpp();	static const std::string classprefix;	static const std::string fullname;	static const std::string classname;private:	static MessageCenter *m_instance;	std::List<std::string> m_messageList;};int lua_cocos2dx_MessageCenter_getInstance(lua_State* tolua_S);int lua_cocos2dx_MessageCenter_luaGetMessageFromCpp(lua_State* tolua_S);int lua_cocos2dx_MessageCenter_cppSendMessagetoJava(lua_State* tolua_S);//voID Java_org_cocos2dx_lua_AppActivity_javaSendMessagetoCpp(jnienv env,jobject thiz,Jstring msg)#endif



2.MessageCenter.cpp
#include "MessageCenter.h"#include "tolua_fix.h"#include "LuaBasicConversions.h"#include <stdlib.h>#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)#include <jni.h>#include <androID/log.h>#include "platform/androID/jni/JniHelper.h"#define  LOG_TAG    "MessageCenter"#define  LOGD(...)  __androID_log_print(ANDROID_LOG_DEBUG,LOG_TAG,__VA_ARGS__)#endifusing namespace cocos2d;const std::string MessageCenter::classprefix = "cp";const std::string MessageCenter::classname = "MessageCenter";const std::string MessageCenter::fullname = classprefix + "." + classname;MessageCenter *MessageCenter::m_instance = NulL;MessageCenter::MessageCenter(voID){	m_messageList.clear();}MessageCenter::~MessageCenter(voID){}MessageCenter * MessageCenter::getInstance(){	if (!m_instance){		m_instance = new MessageCenter();	}	return m_instance;}const std::string  MessageCenter::luaGetMessageFromCpp(){	if(!m_messageList.empty())	{		const std::string message = m_messageList.front();		m_messageList.pop_front();		return message;	}	return "0";}voID MessageCenter::addMessagetoList(const std::string &message){	m_messageList.push_back(message);}voID MessageCenter::cppSendMessagetoJava(const std::string & message){	cclOG("sendMessagetoJava:%s",message.c_str());	#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)				JniMethodInfo jmi;		JniHelper::getStaticmethodInfo(jmi,"org/cocos2dx/lua/AppActivity","SendMessage","(Ljava/lang/String;)V");		Jstring str = (jmi.env->NewStringUTF(message.c_str()));		jmi.env->CallStaticVoIDMethod(jmi.classID,jmi.methodID,str);	#endif}#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)extern "C"{		voID Java_org_cocos2dx_lua_AppActivity_javaSendMessagetoCpp(jnienv env,Jstring msg)		{			std::string str = JniHelper::Jstring2string(msg);			LOGD("javaSendMessagetoCpp");			MessageCenter::getInstance()->addMessagetoList(str);		}}#endif//==============lua bind================int MessageCenter::lua_bind_AllFunction(lua_State* tolua_S){		lua_getglobal(tolua_S,"_G");		if (lua_istable(tolua_S,-1))//stack:...,_G,{			tolua_open(tolua_S);					tolua_module(tolua_S,classprefix.c_str(),0);			tolua_beginmodule(tolua_S,classprefix.c_str());			tolua_usertype(tolua_S,MessageCenter::fullname.c_str());			tolua_cclass(tolua_S,classname.c_str(),MessageCenter::fullname.c_str(),"",nullptr);			tolua_beginmodule(tolua_S,classname.c_str());				tolua_function(tolua_S,"getInstance",lua_cocos2dx_MessageCenter_getInstance);				tolua_function(tolua_S,"cppSendMessagetoJava",lua_cocos2dx_MessageCenter_cppSendMessagetoJava);				tolua_function(tolua_S,"luaGetMessageFromCpp",lua_cocos2dx_MessageCenter_luaGetMessageFromCpp);			tolua_endmodule(tolua_S);			g_luaType[typeID(MessageCenter).name()] = MessageCenter::fullname;			g_typeCast[classname] = MessageCenter::fullname;						tolua_endmodule(tolua_S);		}		lua_pop(tolua_S,1);	return 1;}int lua_cocos2dx_MessageCenter_getInstance(lua_State* tolua_S){    int argc = 0;	MessageCenter* parentOfFunction = nullptr;	const std::string &functionString = "'lua_cocos2dx_MessageCenter_getInstance'";	const std::string &luaFunctionString = MessageCenter::fullname + ":getInstance";#if COCOS2D_DEBUG >= 1	tolua_Error tolua_err;	if (!tolua_isusertable(tolua_S,1,&tolua_err))	{		  tolua_error(tolua_S,("#ferror in function " + functionString).c_str(),&tolua_err);		  return 0;	}	parentOfFunction = (MessageCenter*)tolua_tousertype(tolua_S,0);	 if (!parentOfFunction)     {		//tolua_error(tolua_S,("invalID 'cobj' in function " + functionString).c_str(),nullptr);        //return 0;    }#endif    argc = lua_gettop(tolua_S) - 1;    if (argc == 0)    {		MessageCenter* ret = MessageCenter::getInstance();        object_to_luaval<MessageCenter>(tolua_S,(MessageCenter*)ret);        return 1;    }    else 		{luaL_error(tolua_S,"%s has wrong number of arguments: %d,was expecting %d \n",luaFunctionString.c_str(),argc,1);}    return 0;}int lua_cocos2dx_MessageCenter_cppSendMessagetoJava(lua_State* tolua_S){    int argc = 0;	MessageCenter* parentOfFunction = nullptr;    bool ok  = true;	const std::string &functionString = "'lua_cocos2dx_MessageCenter_cppSendMessagetoJava'";	const std::string &luaFunctionString = MessageCenter::fullname + ":cppSendMessagetoJava";#if COCOS2D_DEBUG >= 1	tolua_Error tolua_err;	if (!tolua_isusertype(tolua_S,&tolua_err);		  return 0;	}#endif    parentOfFunction = (MessageCenter*)tolua_tousertype(tolua_S,0);#if COCOS2D_DEBUG >= 1    if (!parentOfFunction)     {		tolua_error(tolua_S,nullptr);        return 0;    }#endif    argc = lua_gettop(tolua_S)-1;    if (argc == 1)     {        std::string arg0;		ok &= luaval_to_std_string(tolua_S,2,&arg0,luaFunctionString.c_str());        if(!ok)        {			tolua_error(tolua_S,("invalID arguments in function " + functionString).c_str(),nullptr);            return 0;        }		parentOfFunction->cppSendMessagetoJava(arg0);        lua_settop(tolua_S,1);        return 1;    }	else	{luaL_error(tolua_S,1);}    return 0;}int lua_cocos2dx_MessageCenter_luaGetMessageFromCpp(lua_State* tolua_S){    int argc = 0;	MessageCenter* parentOfFunction = nullptr;    bool ok  = true;	const std::string &functionString = "'lua_cocos2dx_MessageCenter_luaGetMessageFromCpp'";	const std::string &luaFunctionString = MessageCenter::fullname + ":luaGetMessageFromCpp";#if COCOS2D_DEBUG >= 1	 tolua_Error tolua_err;	if (!tolua_isusertype(tolua_S,nullptr);        return 0;    }#endif		argc = lua_gettop(tolua_S) - 1;    if (argc == 0)     {		const std::string &ret = parentOfFunction->luaGetMessageFromCpp();		tolua_pushcppstring(tolua_S,ret);        return 1;    }	else	{luaL_error(tolua_S,1);}	return 0;}



3. 在AppDelegate.cpp中注册MessageCenter函数
bool AppDelegate::applicationDIDFinishLaunching(){    // set default FPS    Director::getInstance()->setAnimationInterval(1.0 / 60.0f);       // register lua module    auto engine = LuaEngine::getInstance();    ScriptEngineManager::getInstance()->setScriptEngine(engine);    lua_State* L = engine->getLuaStack()->getLuaState();    lua_module_register(L);	register_TestLayer(L);	TestClass::lua_bind_AllFunction(L);	MessageCenter::lua_bind_AllFunction(L);	ScreenMatchLayer::lua_bind_AllFunction(L);    // If you want to use Quick-Cocos2d-X,please uncomment below code    // register_all_quick_manual(L);    LuaStack* stack = engine->getLuaStack();    stack->setXXTEAKeyAndSign("2dxLua",strlen("2dxLua"),"XXTEA",strlen("XXTEA"));        //register custom function    //LuaStack* stack = engine->getLuaStack();    //register_custom_function(stack->getLuaState());    #if (COCOS2D_DEBUG > 0) && (CC_CODE_IDE_DEBUG_SUPPORT > 0)    // NOTE:Please don't remove this call if you want to deBUG with Cocos Code IDE    RuntimeEngine::getInstance()->start();    cocos2d::log("iShow!");#else    if (engine->executeScriptfile("src/main.lua"))    {        return false;    }#endif        return true;}



4. org.cocos2dx.lua.AppActivity的java文件(AppActivity.java)
/****************************************************************************copyright (c) 2008-2010 Ricardo Quesadacopyright (c) 2010-2012 cocos2d-x.orgcopyright (c) 2011      Zynga Inc.copyright (c) 2013-2014 Chukong TechnologIEs Inc. http://www.cocos2d-x.orgPermission is hereby granted,free of charge,to any person obtaining a copyof this software and associated documentation files (the "Software"),to dealin the Software without restriction,including without limitation the rightsto use,copy,modify,merge,publish,distribute,sublicense,and/or sellcopIEs of the Software,and to permit persons to whom the Software isfurnished to do so,subject to the following conditions:The above copyright notice and this permission notice shall be included inall copIEs or substantial portions of the Software.THE SOFTWARE IS PROVIDED "AS IS",WITHOUT WARRANTY OF ANY KIND,EXPRESS ORIMPLIED,INCLUDING BUT NOT liMITED TO THE WARRANTIES OF MERCHANTABIliTY,fitness FOR A PARTIculaR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THEAUTHORS OR copYRIGHT HolDERS BE liABLE FOR ANY CLaim,damAGES OR OTHERliABIliTY,WHETHER IN AN ACTION OF CONTRACT,TORT OR OTHERWISE,ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEAliNGS INTHE SOFTWARE.****************************************************************************/package org.cocos2dx.lua;import java.net.InetAddress;import java.net.NetworkInterface;import java.net.socketException;import java.util.Enumeration;import java.util.ArrayList;import org.cocos2dx.lib.Cocos2dxActivity;import androID.app.AlertDialog;import androID.content.Context;import androID.content.DialogInterface;import androID.content.DialogInterface.OnClickListener;import androID.content.Intent;import androID.content.pm.ApplicationInfo;import androID.content.pm.ActivityInfo;import androID.net.ConnectivityManager;import androID.net.NetworkInfo;import androID.net.wifi.WifiInfo;import androID.net.wifi.WifiManager;import androID.os.Bundle;import androID.os.Handler;import androID.os.Message;import androID.provIDer.Settings;import androID.text.format.Formatter;import androID.util.Log;import androID.vIEw.KeyEvent;import androID.vIEw.WindowManager;import androID.Widget.Toast;public class AppActivity extends Cocos2dxActivity{	private static Handler handler;	    static String hostIpadress = "0.0.0.0";        @OverrIDe    protected voID onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);                if(nativeIsLandScape()) {            setRequestedOrIEntation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE);        } else {            setRequestedOrIEntation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT);        }                        final String packagename = this.getPackagename();        final String ipAddress = this.getHostIpAddress();        final String macAddress = this.getMacAddress();        handler = new Handler() {			@OverrIDe			public voID handleMessage(Message msg) {				super.handleMessage(msg);				String message = (String) msg.obj;								if(message.equals("love")){					Log.i("wc","islove");										AppActivity.javaSendMessagetoCpp("2001|" + packagename);					AppActivity.javaSendMessagetoCpp("2002|" + ipAddress);					AppActivity.javaSendMessagetoCpp("2003|" + macAddress);				}								Log.i("wc",message);			}		};			        //2.Set the format of window                // Check the wifi is opened when the native is deBUG.        if(nativeIsDeBUG())        {            getwindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);            if(!isNetworkConnected())            {                AlertDialog.Builder builder=new AlertDialog.Builder(this);                builder.setTitle("Warning");                builder.setMessage("Please open WIFI for deBUGing...");                builder.setPositivebutton("OK",new DialogInterface.OnClickListener() {                                        @OverrIDe                    public voID onClick(DialogInterface dialog,int which) {                        startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));                        finish();                        System.exit(0);                    }                });                builder.setNegativebutton("Cancel",null);                builder.setCancelable(true);                builder.show();            }            hostIpadress = getHostIpAddress();        }    }    private boolean isNetworkConnected() {            ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);              if (cm != null) {                  NetworkInfo networkInfo = cm.getActiveNetworkInfo();              ArrayList networkTypes = new ArrayList();            networkTypes.add(ConnectivityManager.TYPE_WIFI);            try {                networkTypes.add(ConnectivityManager.class.getDeclaredFIEld("TYPE_ETHERNET").getInt(null));            } catch (NoSuchFIEldException nsfe) {            }            catch (illegalaccessexception iae) {                throw new RuntimeException(iae);            }            if (networkInfo != null && networkTypes.contains(networkInfo.getType())) {                    return true;                  }              }              return false;          }          public String getHostIpAddress() {        WifiManager wifimgr = (WifiManager) getSystemService(WIFI_SERVICE);        WifiInfo wifiInfo = wifimgr.getConnectionInfo();        int ip = wifiInfo.getIpAddress();        return ((ip & 0xFF) + "." + ((ip >>>= 8) & 0xFF) + "." + ((ip >>>= 8) & 0xFF) + "." + ((ip >>>= 8) & 0xFF));    }        public static String getLocalipAddress() {        return hostIpadress;    }        private voID exitApp(){    	new AlertDialog.Builder(this).setTitle("退出").setMessage("是否退出游戏")		.setPositivebutton("是",new OnClickListener() {			@OverrIDe			public voID onClick(DialogInterface dialog,int which) {				AppActivity.this.finish();				System.exit(0);			}		}).setNegativebutton("否",int which) {			}		}).show();    }        private static native boolean nativeIsLandScape();    private static native boolean nativeIsDeBUG();	private static native voID javaSendMessagetoCpp(String msg);    @OverrIDe	public boolean onKeyUp(int keyCode,KeyEvent event) {		if (keyCode == KeyEvent.KEYCODE_BACK) {			exitApp();			return true;		}		return super.onKeyUp(keyCode,event);	}            public String getMacAddress()    {    	WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);    	     	WifiInfo info = wifi.getConnectionInfo();    	     	return info.getMacAddress();    }    public static voID SendMessage(String msg) {        Message message = Message.obtain();        message.obj = msg;        AppActivity.handler.sendMessage(message);    }}

5. lua中的调用方法

Utility.lua

cc.const = function()    if cc.const == nil then        cc.const = {}        cc._const = {}        local function newIndex(t,k,v)            if not cc._const[k] then                cc._const[k] = v            else                error("尝试给 const."..k.." 赋值")            end        end        local mt = {        __newindex = newIndex,__index = cc._const        }        setMetatable(cc.const,mt)    end    return cc.constendlocal getPackagename = function(msgArray)    cc.showtextTips("getPackagename:" .. msgArray[2])endlocal getIpAddress = function(msgArray)    cc.showtextTips("getIpAddress:" .. msgArray[2])endlocal getMacAddress = function(msgArray)    cc.showtextTips("getMacAddress:" .. msgArray[2])end cc.androID = {    packagename = "",ip = "",mac = "",eventList = {        ["2001"] = getPackagename,["2002"] = getIpAddress,["2003"] = getMacAddress    },}cc.zOrder = {    showtextTips = 100}function cc.splitStringWithSeparator(str,split_char)    local sub_str_tab = {};    while (true) do        local pos = string.find(str,split_char);        if (not pos) then            sub_str_tab[#sub_str_tab + 1] = str;            break;        end        local sub_str = string.sub(str,pos - 1);        sub_str_tab[#sub_str_tab + 1] = sub_str;        str = string.sub(str,pos + 1,#str);    end    return sub_str_tab;endfunction cc.startListenCppMessage()     local function event_loop(dtime)         local msg = cp.MessageCenter : getInstance() : luaGetMessageFromCpp()        if msg ~= nil and msg ~= "0" then            local msgArray = cc.splitStringWithSeparator(msg,"|")            local code = msgArray[1]            if #msgArray > 0 and cc.androID.eventList[code] ~= nil then                cc.androID.eventList[code](msgArray)            end        end    end    cc.Director : getInstance() : getScheduler() : scheduleScriptFunc(event_loop,0.1,false)endfunction cc.showtextTips(text)    local scene = cc.Director:getInstance() : getRunningScene()    if scene ~= nil and text ~= "" then        local function createTextBackgrounDWithSize(bgSize)            local bgSprite = ccui.Scale9Sprite:create("tips/ui_bg_small.png")            bgSprite : setScale9Enabled(true)            bgSprite : setContentSize(bgSize)            bgSprite : setLocalZOrder(cc.zOrder.showtextTips)            bgSprite : setposition(480,320)            return bgSprite        end        local label = cc.LabelTTF:create(text,"heiti",24)        local bgSize = cc.size(label : getContentSize().wIDth + 40,50)        local bgSprite = createTextBackgrounDWithSize(bgSize)        scene : addChild(bgSprite)                bgSprite : addChild(label)        label : setposition(bgSize.wIDth / 2,bgSize.height / 2)        local actionMove = cc.Sequence:create(              cc.MoveBy:create(1.0,cc.p(0,100)),cc.DelayTime:create(0.5),cc.CallFunc:create(                 function ()                     bgSprite : removeFromParent()                end)        )        bgSprite : runAction(actionMove)    else        print("showtextTips error")    endend
总结

以上是内存溢出为你收集整理的cocos2dx-lua编程之c++与lua通信,c++与java通信全部内容,希望文章能够帮你解决cocos2dx-lua编程之c++与lua通信,c++与java通信所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1077958.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-27
下一篇 2022-05-27

发表评论

登录后才能评论

评论列表(0条)

保存