1. 注册Jsb函数
(1)首先在项目目录下的frameworks/runtime-src/Classes/目录添加Jsb_ios_info.h的头文件,内容如下:
//#include <stdio.h>
#include "cocos2d_specifics.hpp"
#include "cocos2d.h"
#import "sys/sysctl.h"
std::string os_info();
bool Jsb_os_info(jscontext *cx,uint32_t argc,Js::Value *vp);
voID register_Jsb_os_info(jscontext *cx,JsObject* obj);
(2)增加Jsb_ios_info.mm文件,内容如下:
#include "Jsb_ios_info.h"
std::string os_info(){
size_t size;
int nR = sysctlbyname("hw.machine",NulL,&size,0);
char *machine = (char *)malloc(size);
nR = sysctlbyname("hw.machine",machine,0);
Nsstring *platform = [Nsstring stringWithCString:machine enCoding:NSUTF8StringEnCoding];
free(machine);
if ([platform isEqualToString:@"iphone4,1"]) {
platform = @"iphone 4s";
}else{
platform = @"iphone others .";
}
Nsstring *info = [Nsstring stringWithFormat:@"%@|%@",platform,[UIDevice currentDevice].systemVersion];
std::string *str = new std::string([info UTF8String]);
return *str;
}
bool Jsb_os_info(jscontext *cx,Js::Value *vp){
Jsval ret = std_string_to_Jsval(cx,os_info());
Js_SET_RVAL(cx,vp,ret);
return true;
}
voID register_Jsb_os_info(jscontext *cx,JsObject* obj){
Js_defineFunction(cx,obj,"osInfo",Jsb_os_info,0);
}
(3)然后修改同目录下AppDelegate.cpp文件,添加相应的引用和注册JavaScript函数:
#include "Jsb_ios_info.h"
sc->addRegisterCallback(register_Jsb_os_info);
涉及平台,要写在
if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS || CC_TARGET_PLATFORM == CC_PLATFORM_MAC)里边。
(4)Js调用
cc.log(osInfo());
即可输出结果:
Js: iphone others .|7.1
总结以上是内存溢出为你收集整理的Cocos2d-js 3.0 jsb环境调用底层Objective-C代码全部内容,希望文章能够帮你解决Cocos2d-js 3.0 jsb环境调用底层Objective-C代码所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)