Java side:
NativeLib.java
Code:
package com.company.game;
public class NativeLib
{
//Java declarations of native functions. Key word here is native.
public static native int init();
public static native int somefunction(int x, int y, String cad);
// Java functions that will be called from C++
private static void javanamefunction(String str, double x)
{
//Here In-app purchases calls.
}
}
C++ side (file inside jni folder)
NativeInterface.cpp
Code:
#include <jni.h> //The important header
#include <string>
static JavaVM* s_vm = 0;
jclass libClass;
jmethodID javanamefunctionMethod;
JavaVM* ME_JavaVM()
{
return s_vm;
}
extern "C"
{
// Java => C++ methods. The name must be [Java_] + [PackageName] + [Filename] + [Function name]. And of course parameters must be the same.
JNIEXPORT jint JNICALL Java_com_company_game_NativeLib_init(JNIEnv* env, jobject obj);
JNIEXPORT void JNICALL Java_com_company_game_NativeLib_somefunction(JNIEnv * env, jobject obj, int x, int y, jstring cad);
}
JNIEXPORT jint JNICALL Java_com_company_game_NativeLib_init(JNIEnv* env, jobject obj)
{
// Obtain the Java class.
env->GetJavaVM(&s_vm);
libClass = env->FindClass("com/company/game/NativeLib");
assert(libClass);
// C++ => Java methods.
javanamefunctionMethod = env->GetStaticMethodID(libClass, "javanamefunction", "(Ljava/lang/String;D)V");
assert(javanamefunctionMethod);
return 0;
}
JNIEXPORT void JNICALL Java_com_company_game_NativeLib_somefunction(JNIEnv * env, jobject obj, int x, int y, jstring cad)
{
const char *convstr = env->GetStringUTFChars(cad, 0);
//Operations with convstr;
env->ReleaseStringUTFChars(cad, convstr);
}
// C++ => Java
void android_paymoney(const char* id, double money)
{
JavaVM* vm = ME_JavaVM();
JNIEnv* env = 0;
int vm_attached = vm->GetEnv((void**)&env, JNI_VERSION_1_6);
assert(env);
assert( vm_attached == JNI_OK );
env->CallStaticVoidMethod(libClass, javanamefunctionMethod, id, money);
}
First you must call init() (from Java). I do it when creating the GLView, we need investigate where to call this because it should depend of Esenthel intialization.
- How to call c++ functions from Java?
NativeLib.init();
NativeLib.somefunction(5,5,"hi");
- How to call java functions from c++?
extern android_paymoney(const char* id, double money); // Declare this line at the begining of the file for example
android_paymoney("weapon2", 10000);
----------
Of course you need to learn how to pass variables, I did put some examples with strings, ints and doubles.
I hope it helps.