官方教程传送门http://www.cocos2d-x.org/docs/manual/framework/native/wiki/how-to-use-bindings-generator/zh
目前还不会lua传 函数 给c++ 类 执行
ini文件 [network_srv] #theprefixtobeaddedtothegeneratedfunctions.Youmightormightnotusethisinyourown #templates prefix=network_srv #createatargetnamespace(injavascript,thiswouldcreatesomecodeliketheequiv.to`ns=ns||{}`) #allclasseswillbeembeddedinthatnamespace target_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/include android_flags=-D_SIZE_T_DEFINED_ clang_headers=-I%(clangllvmdir)s/lib/clang/3.3/include clang_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/lua cocos_flags=-DANDROID cxxgenerator_headers= #extraargumentsforclang extra_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 #whatheaderstoparse headers=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"lookup classes_have_no_parents= #baseclasseswhichwillbeskippedwhentheirsub-classesfoundthem. base_classes_to_skip= #classesthatcreatenoconstructor #Setisspecialandwewilluseahand-writtenconstructor abstract_classes= #Determiningwhethertousescriptobject(jsobject)tocontrolthelifecycleofnative(cpp)objectortheotherwayaround.Supportedvaluesare'yes'or'no'. script_control_cpp=no
genbindings.py文件 #!/usr/bin/python #Thisscriptisusedtogenerateluabindinggluecodes. #Androidndkversionmustbendk-r9b. importsys importos,os.path importshutil importConfigParser importsubprocess importre fromcontextlibimportcontextmanager def_check_ndk_root_env(): '''CheckingtheenvironmentNDK_ROOT,whichwillbeusedforbuilding ''' try: NDK_ROOT=os.environ['NDK_ROOT'] exceptException: print"NDK_ROOTnotdefined.PleasedefineNDK_ROOTinyourenvironment." sys.exit(1) returnNDK_ROOT def_check_python_bin_env(): '''CheckingtheenvironmentPYTHON_BIN,whichwillbeusedforbuilding ''' try: PYTHON_BIN=os.environ['PYTHON_BIN'] exceptException: print"PYTHON_BINnotdefined,usecurrentpython." PYTHON_BIN=sys.executable returnPYTHON_BIN classCmdError(Exception): pass @contextmanager def_pushd(newDir): prevIoUsDir=os.getcwd() os.chdir(newDir) yield os.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"inthepath ndk_root=re.sub(r"\"","",ndk_root) python_bin=_check_python_bin_env() platform=sys.platform ifplatform=='win32': cur_platform='windows' elifplatform=='darwin': cur_platform=platform elif'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_path elifos.path.isdir(x64_llvm_path): llvm_path=x64_llvm_path else: 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')) #saveconfigtofile config=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) #setproperenvironmentvariables if'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_root output_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_root forkeyincmd_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_LENGTH100 classNetMgr { 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()]='\0'; __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; }
lua代码 localfunctionmenuCallbackClose() ifNetMgr:getInstance():isDone()==1then release_print("recvdata"..NetMgr:getInstance():getData()) end end --addhandlerforcloseitem localmenuToolsItem=rootNode:getChildByName("Button_1") menuToolsItem:addTouchEventListener(menuCallbackClose) srv=network_srv:create(); srv:run();