Hi, Fadli here once again.
As I promised in previous post, we will be doing some coding. In this post and subsequent posts, I will show you guys regarding communication between languages natively as I mentioned in the last post. In our case, between C++ to/from Objective-C and between C++ to/from Java.
This is one of many hot topic among beginner developers that required that extra steps to integrate specific platform SDKs or libraries where mostly are written in their specific language. E.g, iOS will be using Objective-C or Swift and Java for Android.
Bare in mind, most of the games may not need this, meaning, C++ is enough to complete a game project. It will be necessary when you want to show Ads for example. Some SDK out there are plug and play, but some are not.
To make that happens, the simplest method is to create a bridge class. That bridge class implementation will create an object which have the native Objective-C codes.
This bridge class also have the Android counterpart. We will be looking into this later. For now, let’s focus on Objective-C first.
For our example, we will show a native browser in our game. The end product at the end of this post is like this:
Create a header in C++ like below:
It is self explanatory. The Method1OpenUrl class has just one static member function open with url argument of string.
For the cpp implementation file looks like this:
As you can see, we have two built-in Cocos2d-x macros to determine which platform this code will be compiled. We leave the Android part for later.
You can also see that we have an extra class which is called Url. This class will contain the Objective-C implementations. We keep it very simple here. You don’t have to worry, the urlObj object will be released automatically! Oh I love modern C++!! :P
Below is the Url class header file codes:
Straight forward here as well.
Let’s take a look at the implementation file below:
Yes, the filetype should be .mm, to tell Objective-C compiler to compile it as C++ instead.
If you have more Objective-C classes, you can add it here as well as to your liking. For our example, we just use the default openUrl function.
Lastly, to use all this, we just need to call in C++ code like this:
Make sure to include the header too:
Yup, I put all source files in a folder for this part of tutorial. Folder structure is as below:
To test this out, you can also get all the codes from my GitHub repository here:
Next post we will continue with Android part of the equation. See you guys in the next one.