How to call objective C from c++ in cocos2d-x | Techbirds

Hi friends. In this tutorial we will learn to call objective C methods from a c++ class in mac OS
Step 1
Create a new Hello World Project. By default you will have HelloWorldScene.cpp, HelloWorldScene.h, AppDelegate.cpp and AppDelegate.h

Step 2
Now create a new File in your classes folder and name it as ObjCCalls or whatever the name you want.Two more classes will be created in that ObjCCalls.h and ObjCCalls.cpp

Step 3
Now rename the ObjCCalls.cpp class to ObjCCalls.mm.
.mm is an objective c++ class where you can code for both the languages

Step 4
Now in your ObjCCalls.h class write the following

class ObjCCalls{ public: static void objectiveC_call(); };

class ObjCCalls{

public:

static void objectiveC_call();

};

We have made a static method so that we can directly call the method with class name from HelloWorld class
Step 5
In your ObjCCalls.cpp define the static method

void ObjCCalls::objectiveC_call() { //your objective c code here NSLog(@”Hello World”); } }

void ObjCCalls::objectiveC_call()

{

//your objective c code here

    NSLog(@”Hello World”);

}

}

Step 6
now in your HelloWorldScene.cpp class, include the ObjCCalls.h class and make a function and define the function as:

#include”ObjCCalls.h”

void HelloWorld::obCCalling() { //calling objective c code ObjCCalls::objectiveC_call(); }

void HelloWorld::obCCalling()

{

   //calling objective c code

   ObjCCalls::objectiveC_call();

}

So now you are able to call the objective code from a c++ class
HAPPY CODING

4,994 total views, 2 views today

Share this Onfacebook-4854993twitter-4618241linkedin-7589586google-7703955