Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@maple-nishiyama
Created December 14, 2015 14:41
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 maple-nishiyama/e4f0be43903af95609d2 to your computer and use it in GitHub Desktop.
Save maple-nishiyama/e4f0be43903af95609d2 to your computer and use it in GitHub Desktop.
Android JNI で C/C++ のポインタを Java に渡す。(C++側のソース)
#include <jni.h>
#include <android/log.h>
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,"NdkPointer", __VA_ARGS__)
static JavaVM* jvm = nullptr;
static JNIEnv* env;
class CppClass {
public:
void callback() {
LOGD("!!!! callback called !!!!");
}
};
extern "C" {
jint JNI_OnLoad(JavaVM* vm, void* reserved) {
jvm = vm;
vm->GetEnv((void**)&env, JNI_VERSION_1_6);
return JNI_VERSION_1_6;
}
void Java_com_example_ndkpointer_MainActivity_nativeMethod() {
LOGD("nativeMethod called");
auto obj = new CppClass();
jclass c = env->FindClass("com/example/ndkpointer/MainActivity");
if (c == nullptr) {
LOGD("class not found.");
return;
}
jmethodID mid = env->GetStaticMethodID(c, "asyncProc", "(J)V");
if (mid == nullptr) {
LOGD("method not found");
return;
}
env->CallStaticVoidMethod(c, mid, reinterpret_cast<jlong>(obj));
}
void Java_com_example_ndkpointer_MainActivity_callback(jlong p) {
CppClass* obj = (CppClass*)p;
obj->callback();
delete obj;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment