cocos2dx系列博文的上一篇详细介绍了如何在xcode中利用jni调用android的java层代码,还没有看过的童鞋,请移步到如下博文:
<a href="http://www.himigame.com/iphone-cocos2dx/www.himigame.com/android-game/725.html">【ios-cocos2d-x 游戏开发之十三】详细讲解在xcode中利用预编译并通过jni调用android的java层代码(cocos2dx里访问调用android函数)! </a>
本篇继续介绍另外一个在cocos2dx中必经之路:在cocos2dx中调用苹果api以实现后期ios的gamecenter和iap的相关操作, 那么himi这里就跟大家简单分享探讨下;如何在xcode中进行c++与oc混编吧~
参考王哥说的 simpleaudioengine 类;
首先himi建立了两个类,一个object-c ,一个c++,详细如下:
hspriteoc.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
//
// hspriteoc.h
// oc_cpp
// created by himi on 12-4-10.
// copyright (c) 2012年 himi. all rights reserved.
#import &lt;foundation/foundation.h&gt;
nsstring * str;
@interface hspriteoc
+(void) testlog;
+(void) testlogwithstr:(nsstring*)_str;
+(void) hmessagebox:(nsstring*)pszmsg title:(nsstring*)psztitle;
@end
hspriteoc.m
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
// hsprite.m
// created by himi on 12-4-10.
#import "hspriteoc.h"
@implementation hspriteoc
+(void) testlog{
str = @"himi-&gt;string is: ";
nslog(@"hsprite: testlog");
}
+(void) testlogwithstr:(nsstring*)_str{
str = [nsstring stringwithformat:@"%@%@",str,_str];
nslog(@"%@",str);
+(void) hmessagebox:(nsstring*)pszmsg title:(nsstring*)psztitle{
uialertview * messagebox = [[uialertview alloc] initwithtitle: psztitle
message: pszmsg
delegate: nil
cancelbuttontitle: @"ok"
otherbuttontitles: nil];
[messagebox autorelease];
[messagebox show];
这个类比较简单,简单定义了几个静态函数,打印和显示一个提示框,不赘述,大家大概看下就可以了;
下面来看c++的类:
hspritecpp.h
// hspritecpp.h
#ifndef oc_cpp_hsprite_h
#define oc_cpp_hsprite_h
#include "cocos2d.h"
using namespace cocos2d;
class hspritecpp:public cocos2d::ccsprite {
public:
static hspritecpp* hspritewithfile(const char *spname);
void myinit();
virtual ~hspritecpp();
};
#endif
hspritecpp.cpp
36
37
38
39
40
41
42
// hspritecpp.mm
#if (cc_target_platform == cc_platform_ios)
#include "hspriteoc.h"
#include "hspritecpp.h"
hspritecpp* hspritecpp::hspritewithfile(const char *spname)
{
hspritecpp *pobsprite = new hspritecpp();
if (pobsprite &amp;&amp; pobsprite-&gt;initwithfile(spname))
{
pobsprite-&gt;myinit();
pobsprite-&gt;autorelease();
return pobsprite;
}
cc_safe_delete(pobsprite);
return null;
void hspritecpp::myinit(){
//ios代码
[hspriteoc testlog];
[hspriteoc testlogwithstr:@"wahaha"];
[hspriteoc hmessagebox:@"cocos2dx调用oc函数" title:@"himi"];
#else
//android代码
hspritecpp::~hspritecpp(){
此类是个自定义精灵类,都是简单的创建等函数,其hsprite.cpp类的导入和在 myinit() 自定义初始化函数中都加入了预编译(#if #else #endif 对预编译不太了解的自定百度下吧),主要为了区别当前手机设备的平台区分做处理;而且在myinit()中我使用了object-c语法进行调用之前oc写的hsprite类函数;
其实通过观察以上两个类童鞋们估计很容易看出在xcode中cpp和oc如何混编;其实就是两点:
1. 混编的类需要将其实现类(.cpp)改成(.mm)类,那么xcode就会智能知道这个类混编类了,不用复杂的操作;
2. 混编中cpp调用oc,其实就是各自使用各自语法即可,没差异!(最好对oc和c++都比较熟悉更效率)
然后himi在helloworldscene.cpp中加入以下测试代码:
hspritecpp * sp =hspritecpp::hspritewithfile("icon.png");
sp-&gt;setposition(ccp(ccdirector::shareddirector()-&gt;getwinsize().width*0.5,ccdirector::shareddirector()-&gt;getwinsize().height*0.5-100));
this-&gt;addchild(sp);
别忘记导入对应使用的类哦~ok,看运行效果: