|
| 1 | +#include <jni.h> |
| 2 | +#include <quickjs.h> |
| 3 | + |
| 4 | +JNIEXPORT jlong JNICALL |
| 5 | +Java_com_hippo_quickjs_android_QuickJS_createRuntime(JNIEnv *env, jclass clazz) { |
| 6 | + return (jlong) JS_NewRuntime(); |
| 7 | +} |
| 8 | + |
| 9 | +JNIEXPORT void JNICALL |
| 10 | +Java_com_hippo_quickjs_android_QuickJS_destroyRuntime(JNIEnv *env, jclass clazz, jlong runtime) { |
| 11 | + JSRuntime *rt = (JSRuntime *) runtime; |
| 12 | + if (rt != NULL) { |
| 13 | + JS_FreeRuntime(rt); |
| 14 | + } |
| 15 | +} |
| 16 | + |
| 17 | +JNIEXPORT jlong JNICALL |
| 18 | +Java_com_hippo_quickjs_android_QuickJS_createContext(JNIEnv *env, jclass clazz, jlong runtime) { |
| 19 | + JSRuntime *rt = (JSRuntime *) runtime; |
| 20 | + if (rt == NULL) { |
| 21 | + return 0; |
| 22 | + } |
| 23 | + return (jlong) JS_NewContext(rt); |
| 24 | +} |
| 25 | + |
| 26 | +JNIEXPORT void JNICALL |
| 27 | +Java_com_hippo_quickjs_android_QuickJS_destroyContext(JNIEnv *env, jclass clazz, jlong context) { |
| 28 | + JSContext *ctx = (JSContext *) context; |
| 29 | + if (ctx != NULL) { |
| 30 | + JS_FreeContext(ctx); |
| 31 | + } |
| 32 | +} |
| 33 | + |
| 34 | +JNIEXPORT jobject JNICALL |
| 35 | +Java_com_hippo_quickjs_android_QuickJS_evaluate(JNIEnv *env, jclass clazz, |
| 36 | + jlong context, jstring source_code, jstring file_name, jint flags) { |
| 37 | + JSContext *ctx = (JSContext *) context; |
| 38 | + if (ctx == NULL || source_code == NULL || file_name == NULL) { |
| 39 | + return 0; |
| 40 | + } |
| 41 | + |
| 42 | + const char *source_code_utf = NULL; |
| 43 | + jsize source_code_length = 0; |
| 44 | + const char *file_name_utf = NULL; |
| 45 | + jobject result = NULL; |
| 46 | + |
| 47 | + source_code_utf = (*env)->GetStringUTFChars(env, source_code, NULL); |
| 48 | + source_code_length = (*env)->GetStringUTFLength(env, source_code); |
| 49 | + file_name_utf = (*env)->GetStringUTFChars(env, file_name, NULL); |
| 50 | + |
| 51 | + if (source_code_utf != NULL && file_name_utf != NULL) { |
| 52 | + JSValue val = JS_Eval(ctx, source_code_utf, (size_t) source_code_length, file_name_utf, flags); |
| 53 | + // TODO val to result |
| 54 | + JS_FreeValue(ctx, val); |
| 55 | + } |
| 56 | + |
| 57 | + if (source_code_utf != NULL) { |
| 58 | + (*env)->ReleaseStringUTFChars(env, source_code, source_code_utf); |
| 59 | + } |
| 60 | + if (file_name_utf != NULL) { |
| 61 | + (*env)->ReleaseStringUTFChars(env, file_name, file_name_utf); |
| 62 | + } |
| 63 | + return result; |
| 64 | +} |
0 commit comments