# Using iOS and Android Libraries in Cocos2D-X

Been working on some libs on both iOS and Android platforms for a long time, recently needed to support Cocos2d-x framework, I have no interest to write a whole new lib based on C++, nightmare for maintenance, So I worked on to integrate both libs to Cocos2d-x framework.

## iOS

Imagine my lib name is libHumbleAssistant.a, with a header file HumbleAssistant.h.

Lucky me, Objective C belongs to C family, which could integrate with C and C++ seamlessly.

At first, create a .h header file as the real interface for C++ code, and name it as humble_assistant_cpp.h.

Then, create its source humble_assistant_cpp.mm, .mm stands for Objective-C++, in which, people can hybrid programming with Objective C and C++.

Now, the file structures looks like this

-mylibs
-ios
- HumbleAssistant.h
- libHumbleAssistant.a
- humble_assistant_cpp.h
- humble_assistant_cpp.mm


In a Cocos2d-x project, add those files, and include the humble_assistant_cpp.h to any C++ code that is about to ask the humble assistant a favor. It’s that simple.

## Android

JNI is used to bind Cocos2d-x and Android Java interfaces.

In order to call a method in a jar lib from C++, JNI code must be written.

Imagine my android lib is humbleAssistant.jar, and has an interface as below.

To expose this method to C++, first, create a header file humble_assistant_jni.h.

Then, its implementation humble_assistant_jni.cpp, a little complicated due to the JNI’s obscure grammar.

Cocos2d-x is a cross platform framework, our libs need to be that too, only one single interface is needed.

In iOS, a humble_assistant_cpp.h is created, which is the universal header file for both platforms. And humble_assistant_cpp.mm is the source file.

So, in Android, we have to make a new source file humble_assistant_cpp.cpp.

Now, the file structures looks like this

-mylibs
-ios
- HumbleAssistant.h
- libHumbleAssistant.a
- humble_assistant_cpp.h
- humble_assistant_cpp.mm
-android
- humble_assistant_jni.h
- humble_assistant_jni.cpp
- humble_assistant_cpp.cpp


But it’s not finished.

We have to change the makefile in “proj.android/jni/android.mk” to add source files and the header file.

And also, put the jar lib into “proj.android/libs” folder.

It’s done. Looks much more complicated than iOS way, and could be even worse.

If the doSomething interface needs a HashMap parameter, JNI code will be full of stupid code.

Feel lucky again that my lib only exposes static methods, with simple parameters.

Maybe that’s why I don’t like cross platform frameworks, and Android.