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, NULL, 0);
char *machine = (char *)malloc(size);
nR = sysctlbyname("hw.machine", machine, &size, NULL, 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, uint32_t argc, 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, 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