Skip to content

Instantly share code, notes, and snippets.

@prespondek
Last active August 29, 2015 14:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save prespondek/6d5939efc2a63371cbdd to your computer and use it in GitHub Desktop.
Save prespondek/6d5939efc2a63371cbdd to your computer and use it in GitHub Desktop.
JNI Demo
#include <jni.h>
#include "platform/android/jni/JniHelper.h"
void CppToJava(const char* str, bool flag)
{
cocos2d::JniMethodInfo t;
if (cocos2d::JniHelper::getStaticMethodInfo( t,
// package and class name with slashes rather than dots
"com/my/package/JNIExample",
// name of java function called
"JavaFromCpp",
// this corresponds to the arguments and return value of the called Java function in reverse.
// http://docs.oracle.com/javase/7/docs/technotes/guides/jni/spec/types.html
"(Ljava/lang/String;[Ljava/lang/String;Z)V"))
{
jstring java_str = t.env->NewStringUTF (str);
// create an array of strings
jclass jStringCls = t.env->FindClass("java/lang/String");
jobjectArray str_array = t.env->NewObjectArray( 2, jStringCls, NULL);
jstring keyString1 = t.env->NewStringUTF("one");
jstring keyString2 = t.env->NewStringUTF("two");
t.env->SetObjectArrayElement(result, 0, keyString1);
t.env->SetObjectArrayElement(result, 1, keyString2);
t.env->CallStaticVoidMethod (t.classID, t.methodID, java_str, str_array, (jboolean)flag);
t.env->DeleteLocalRef (t.classID);
t.env->DeleteLocalRef (java_str);
t.env->DeleteLocalRef (str_array);
}
}
extern "C" {
// The function name here follows a stict naming convention and must be correct in order to recieve call from Java
// First two arguments are always (JNIEnv* env, jclass clazz) the following are those passed from Java function.
JNIEXPORT void JNICALL Java_com_my_package_JNIExample_CppFromJava(JNIEnv* env, jclass clazz, jstring str, jfloat num)
{
std::string cpp_str = cocos2d::JniHelper::jstring2string(str);
float cpp_float = (float)jprice;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment