Created
December 14, 2015 14:41
-
-
Save maple-nishiyama/e4f0be43903af95609d2 to your computer and use it in GitHub Desktop.
Android JNI で C/C++ のポインタを Java に渡す。(C++側のソース)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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