您的位置:首页 > 移动开发 > Cocos引擎

Xcode中c++&Object-C混编,详细介绍如何在cocos2dx中访问object函数

2016-11-30 11:31 525 查看
首先建立了两个类,一个object-c ,一个c++,详细如下:

HSpriteOC.h

#import <Foundation/Foundation.h>

NSString * str;@ interface HSpriteOC

    +(void) testLog;

+(void) testLogWithStr:(NSString*)_str;

+(void) hMessageBox:(NSString*)pszMsg title:(NSString*)pszTitle;

@end

HSpriteOC.m

 #import"HSpriteOC.h"

@implementation HSpriteOC

+(void) testLog{

    str = @"Himi->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];

}

@end

这个类比较简单,简单定义了几个静态函数,打印和显示一个提示框,不赘述,大家大概看下就可以了;

下面来看c++的类:

HSpriteCPP.h

#ifndef Oc_Cpp_HSprite_h#define Oc_Cpp_HSprite_h

#include "cocos2d.h"usingnamespace cocos2d;

class HSpriteCPP:public cocos2d::CCSprite {public:

    static HSpriteCPP* hspriteWithFile(constchar *spName);

    void myInit();

    virtual ~HSpriteCPP();

};#endif

HSpriteCPP.cpp

#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)

#include "HSpriteOC.h"

#endif

#include "HSpriteCPP.h"

HSpriteCPP* HSpriteCPP::hspriteWithFile(constchar *spName)

{

    HSpriteCPP *pobSprite = new HSpriteCPP();

    

    if (pobSprite && pobSprite->initWithFile(spName))

    {

        pobSprite->myInit();

       pobSprite->autorelease();

       return pobSprite;

    }

    CC_SAFE_DELETE(pobSprite);

    return NULL;

}

 void HSpriteCPP::myInit(){#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)

    //iOS代码    [HSpriteOC testLog];

    [HSpriteOC testLogWithStr:@"wahaha"];

    [HSpriteOC hMessageBox:@"cocos2dx调用oc函数" title:@"Himi"];#else

    //Android代码#endif

    

}

  

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->setPosition(ccp(CCDirector::sharedDirector()->getWinSize().width*0.5,CCDirector::sharedDirector()->getWinSize().height*0.5-100));

    this->addChild(sp);

别忘记导入对应使用的类哦~OK,看运行效果:

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐