Cocos2d-js 3.0 jsb环境调用底层Objective-C代码

前端之家收集整理的这篇文章主要介绍了Cocos2d-js 3.0 jsb环境调用底层Objective-C代码前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

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());

即可输出结果:

@H_404_105@JS: iphone others .|7.1

猜你在找的Cocos2d-x相关文章