Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // This is pseudo code, but it gives you an idea of how v8<->JNI might work
- static JavaVM *vm;
- // Called when the shared library is loaded
- extern "C" JNIEXPORT jint JNICALL
- JNI_OnLoad(JavaVM *jvm, void *reserved)
- {
- JNIEnv *env;
- vm = jvm; /* cache the JavaVM pointer */
- if (jvm->GetEnv((void **) &env, JNI_VERSION_1_4)) {
- return JNI_ERR; /* JNI version not supported */
- }
- return JNI_VERSION_1_4;
- }
- jclass objClass;
- jmethodID javaMethodId;
- // V8Main.main(src, name);
- extern "C" JNIEXPORT void JNICALL
- Java_org_appcelerator_kroll_v8_V8Main_main(JNIEnv *env, jobject thiz, jstring source, jstring name)
- {
- HandleScope scope;
- Handle<ObjectTemplate> globalTemplate = ObjectTemplate::New();
- Persistent<Context> context = Context::New(NULL, globalTemplate);
- Context::Scope contextScope(context);
- // Object templates are the way v8 exposes prototypes natively
- // Any object that is created w/ the template has the APIs on the template itself
- Handle<ObjectTemplate> objTemplate = ObjectTemplate::New();
- // To bind a java method, we would first bind a native function pointer
- objTemplate->Set(String::New("javaMethod"), Obj_javaMethod);
- Handle<Object> obj = objTemplate->NewInstance();
- // We wrap the "thiz" pointer into an internal field so it can be fetched
- obj->SetInternalField(0, External::Wrap(reinterpret_cast<void*>(thiz)));
- // Cache the class, and "javaMethod" methodID for later
- objClass = env->FindClass("com/my/Class");
- // javaMethod() is a void method
- javaMethodId = env->GetMethodID(objClass, "javaMethod", "()V");
- // Finally bind "obj" as "helloWorld" in JS land
- context->Global()->Set(String::New("helloWorld"), obj);
- const char *srcData = const_cast<const char *>(env->GetStringUTFChars(source, NULL));
- const char *cName = const_cast<const char *>(env->GetStringUTFChars(name, NULL));
- Local<Script> script = Script::Compile(String::New(srcData), String::New(cName));
- script->Run();
- env->ReleaseStringUTFChars(source, srcData);
- env->ReleaseStringUTFChars(name, cName);
- context.Dispose();
- }
- static Handle<Value> Obj_javaMethod(const Arguments& args)
- {
- // get the java pointer
- jobject obj = reinterpret_cast<jobject>(External::Unwrap(args.This()->GetInternalField(0)));
- // get the JNIEnv
- JNIEnv *env;
- vm->GetEnv((void **) &env, JNI_VERSION_1_4);
- env->CallVoidMethod(obj, javaMethodId);
- return Undefined();
- }
- ## test.js
- helloWorld.javaMethod();
Add Comment
Please, Sign In to add comment