官方教程传送门http://www.cocos2d-x.org/docs/manual/framework/native/wiki/how-to-use-bindings-generator/zh
..编辑 ini文件
修改py脚本内容
运行py工具
就可以使用了
目前还不会lua传 函数 给c++ 类 执行
ini文件[network_srv]#theprefixtobeaddedtothegeneratedfunctions.Youmightormightnotusethisinyourown#templatesprefix=network_srv#createatargetnamespace(inJavaScript,thiswouldcreatesomecodeliketheequiv.to`ns=ns||{}`)#allclasseswillbeembeddedinthatnamespacetarget_namespace=androID_headers=-I%(androIDndkdir)s/platforms/androID-14/arch-arm/usr/include-I%(androIDndkdir)s/sources/cxx-stl/gnu-libstdc++/4.7/libs/armeabi-v7a/include-I%(androIDndkdir)s/sources/cxx-stl/gnu-libstdc++/4.7/include-I%(androIDndkdir)s/sources/cxx-stl/gnu-libstdc++/4.8/libs/armeabi-v7a/include-I%(androIDndkdir)s/sources/cxx-stl/gnu-libstdc++/4.8/includeandroID_flags=-D_SIZE_T_defineD_clang_headers=-I%(clangllvmdir)s/lib/clang/3.3/includeclang_flags=-nostdinc-xc++-std=c++11-U__SSE__cocos_headers=-I%(cocosdir)s/cocos-I%(cocosdir)s/cocos/platform/androID-I%(cocosdir)s/cocos/editor-support-I%(cocosdir)s/external-I%(cocosdir)s/cocos/scripting/lua-bindings/manual-I%(cocosdir)s/external/lua/lua-I%(cocosdir)s/external/luacocos_flags=-DANDROIDcxxgenerator_headers=#extraargumentsforclangextra_arguments=%(androID_headers)s%(clang_headers)s%(cxxgenerator_headers)s%(cocos_headers)s%(androID_flags)s%(clang_flags)s%(cocos_flags)s%(extra_flags)s#whatheaderstoparseheaders=C:/Users/hk/documents/Cocos/CocosProjects/LuaTest/frameworks/runtime-src/Classes/network_srv.h#whatclassestoproducecodefor.YoucanuseregularExpressionshere.Whentestingtheregular#Expression,itwillbeenclosedin"^$",likethis:"^Menu*$".classes=network_srvNetMgr#whatshoulDWeskip?intheformatClassname::[functionfunction]#ClassnameisaregularExpression,butwillbeusedlikethis:"^Classname$"functionsarealso#regularExpressions,theywillnotbesurroundedby"^$".Ifyouwanttoskipawholeclass,just#addasingle"*"asfunctions.Seebellowforseveralexamples.Aspecialclassnameis"*",which#willapplytoallclassnames.ThisisaconvenIEncewildcardtobeabletoskipsimilarnamed#functionsfromallclasses.skip=rename_functions=rename_classes=#forallclassnames,shoulDWeremovesomethingwhenregisteringinthetargetVM?remove_prefix=#classesforwhichtherewillbeno"parent"lookupclasses_have_no_parents=#baseclasseswhichwillbeskippeDWhentheirsub-classesfoundthem.base_classes_to_skip=#classesthatcreatenoconstructor#SetisspecialanDWewilluseahand-writtenconstructorabstract_classes=#Determiningwhethertousescriptobject(Jsobject)tocontrolthelifecycleofnative(cpp)objectortheotherwayaround.Supportedvaluesare'yes'or'no'.script_control_cpp=no
genbindings.py文件#!/usr/bin/python#Thisscriptisusedtogenerateluabindinggluecodes.#AndroIDndkversionmustbendk-r9b.importsysimportos,os.pathimportshutilimportConfigParserimportsubprocessimportrefromcontextlibimportcontextmanagerdef_check_ndk_root_env():'''CheckingtheenvironmentNDK_ROOT,whichwillbeusedforbuilding'''try:NDK_ROOT=os.environ['NDK_ROOT']exceptException:print"NDK_ROOTnotdefined.PleasedefineNDK_ROOTinyourenvironment."sys.exit(1)returnNDK_ROOTdef_check_python_bin_env():'''CheckingtheenvironmentPYTHON_BIN,whichwillbeusedforbuilding'''try:PYTHON_BIN=os.environ['PYTHON_BIN']exceptException:print"PYTHON_BINnotdefined,usecurrentpython."PYTHON_BIN=sys.executablereturnPYTHON_BINclassCmdError(Exception):pass@contextmanagerdef_pushd(newDir):prevIoUsDir=os.getcwd()os.chdir(newDir)yIEldos.chdir(prevIoUsDir)def_run_cmd(command):ret=subprocess.call(command,shell=True)ifret!=0:message="Errorrunningcommand"raiseCmdError(message)defmain():cur_platform='??'llvm_path='??'ndk_root=_check_ndk_root_env()#delthe"inthepathndk_root=re.sub(r"\"","",ndk_root)python_bin=_check_python_bin_env()platform=sys.platformifplatform=='win32':cur_platform='windows'elifplatform=='darwin':cur_platform=platformelif'linux'inplatform:cur_platform='linux'else:print'Yourplatformisnotsupported!'sys.exit(1)ifplatform=='win32':x86_llvm_path=os.path.abspath(os.path.join(ndk_root,'toolchains/llvm-3.3/prebuilt','%s'%cur_platform))else:x86_llvm_path=os.path.abspath(os.path.join(ndk_root,'%s-%s'%(cur_platform,'x86')))x64_llvm_path=os.path.abspath(os.path.join(ndk_root,'x86_64')))ifos.path.isdir(x86_llvm_path):llvm_path=x86_llvm_pathelifos.path.isdir(x64_llvm_path):llvm_path=x64_llvm_pathelse:print'llvmtoolchainnotfound!'print'path:%sorpath:%sarenotvalID!'%(x86_llvm_path,x64_llvm_path)sys.exit(1)project_root=os.path.abspath(os.path.join(os.path.dirname(__file__),'..','..'))cocos_root=os.path.abspath(os.path.join(project_root,''))cxx_generator_root=os.path.abspath(os.path.join(project_root,'tools/bindings-generator'))#saveconfigtofileconfig=ConfigParser.ConfigParser()config.set('DEFAulT','androIDndkdir',ndk_root)config.set('DEFAulT','clangllvmdir',llvm_path)config.set('DEFAulT','cocosdir',cocos_root)config.set('DEFAulT','cxxgeneratordir',cxx_generator_root)config.set('DEFAulT','extra_flags','')#Tofixparseerroronwindows,wemustdifine__WCHAR_MAX__andundefine__MINGW32__.ifplatform=='win32':config.set('DEFAulT','-D__WCHAR_MAX__=0x7fffffff-U__MINGW32__')conf_ini_file=os.path.abspath(os.path.join(os.path.dirname(__file__),'userconf.ini'))print'generatinguserconf.ini...'withopen(conf_ini_file,'w')asconfigfile:config.write(configfile)#setproperenvironmentvariablesif'linux'inplatformorplatform=='darwin':os.putenv('LD_liBRARY_PATH','%s/libclang'%cxx_generator_root)ifplatform=='win32':path_env=os.environ['PATH']os.putenv('PATH',r'%s;%s\libclang;%s\tools\win32;'%(path_env,cxx_generator_root,cxx_generator_root))try:tolua_root='%s/tools/tolua'%project_rootoutput_dir='C:/Users/hk/documents/Cocos/CocosProjects/LuaTest/frameworks/runtime-src/Classes'cmd_args={'network_srv.ini':('network_srv','lua_network_srv_auto')}target='lua'generator_py='%s/generator.py'%cxx_generator_rootforkeyincmd_args.keys():args=cmd_args[key]cfg='%s/%s'%(tolua_root,key)print'Generatingbindingsfor%s...'%(key[:-4])command='%s%s%s-s%s-t%s-o%s-n%s'%(python_bin,generator_py,cfg,args[0],target,output_dir,args[1])_run_cmd(command)ifplatform=='win32':with_pushd(output_dir):_run_cmd('dos2unix*')print'---------------------------------'print'Generatingluabindingssucceeds.'print'---------------------------------'exceptExceptionase:ife.__class__.__name__=='CmdError':print'---------------------------------'print'Generatingluabindingsfails.'print'---------------------------------'os.system("pause")else:raise#--------------main--------------if__name__=='__main__':main()
测试代码
network_srv.h文件#ifndefnetwork_srv___#definenetwork_srv___#include"cocos2d.h"#include"network/httpRequest.h"#include"network/httpClIEnt.h"#include"network/httpResponse.h"usingnamespacecocos2d;usingnamespacecocos2d::network;usingnamespacestd;classnetwork_srv:publiccocos2d::Ref{public: CREATE_FUNC(network_srv); boolinit(){returntrue;} network_srv() { this->retain(); } voIDrun();}; #defineURL_BASE"http://127.0.0.1:8080/cocos/" //#defineURL_BASE"http://qq771911064.oicp.net:8080/cocos/"#defineDATA_MAX_LENGTH100classNetMgr{public: staticNetMgr*getInstance(); /** *@brIEfnewahttpRequest *@paramactionsuchas"login?name=1&&pass=1" *@ */ voIDnewRequest(constchar*action); /** *@brIEfifisDonepleasecallthistogetdata *@returndatafromsrv *@ */ constchar*getData(); /** *@brIEfchecknetworkisdoneornot *@return0is'tcompleted *@retuen1completed */ intisDone();private: NetMgr(); int__isDone;/*0is'sdone,1done*/ char_data[DATA_MAX_LENGTH];};#endif//
cpp代码#include"network_srv.h"voIDnetwork_srv::run(){ NetMgr::getInstance()->newRequest("login?name=1&&pass=1");}voIDNetMgr::newRequest(constchar*action){ __isDone=0; stringurl=URL_BASE; url+=action; httpRequest*request=newhttpRequest; request->setUrl(url.c_str()); request->setRequestType(httpRequest::Type::GET); request->setResponseCallback([=](httpClIEnt*clIEnt,httpResponse*respone) { if(respone->getResponseCode()!=200)return; vector<char>*buffer=respone->getResponseData(); CC_ASSERT(DATA_MAX_LENGTH>buffer->size(),"NetMgrbuffersizeoverfloaw"); for(inti=0;i<buffer->size();i++) { _data[i]=(*buffer)[i]; } _data[buffer->size()]='lua代码localfunctionmenuCallbackClose()ifNetMgr:getInstance():isDone()==1thenrelease_print("recvdata"..NetMgr:getInstance():getData())endend--addhandlerforcloseitemlocalmenuToolsItem=rootNode:getChildByname("button_1")menuToolsItem:addtouchEventListener(menuCallbackClose)srv=network_srv:create();srv:run();'; __isDone=1; }); httpClIEnt::getInstance()->setTimeoutForConnect(10); httpClIEnt::getInstance()->send(request); request->release();}NetMgr*NetMgr::getInstance(){ staticNetMgr*_netmgr__=0; if(_netmgr__==0) { _netmgr__=newNetMgr; } return_netmgr__;}constchar*NetMgr::getData(){ __isDone=0; return_data;}intNetMgr::isDone(){ return__isDone;}NetMgr::NetMgr(){ __isDone=0;}
以上是内存溢出为你收集整理的cocos2dx 导出c++类供lua使用全部内容,希望文章能够帮你解决cocos2dx 导出c++类供lua使用所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)