Skip to content

Instantly share code, notes, and snippets.

@RajithaKumara
Created November 12, 2019 10:33
Show Gist options
  • Save RajithaKumara/d387313739e12bd0c1ad69c20e1f2880 to your computer and use it in GitHub Desktop.
Save RajithaKumara/d387313739e12bd0c1ad69c20e1f2880 to your computer and use it in GitHub Desktop.
#include <stdlib.h>
#include <jni.h>
#include <libplatform/libplatform.h>
#include <v8.h>
//...
void runV8(JNIEnv *env, jobject instance, jobjectArray args) {
const char *path_to_snapshot = "";// Get path from args
const char *source_code = "";// Get source code from args
v8::V8::InitializeICU();
v8::V8::InitializeExternalStartupData(path_to_snapshot);
std::unique_ptr<v8::Platform> platform = v8::platform::NewDefaultPlatform();
v8::V8::InitializePlatform(platform.get());
v8::V8::Initialize();
v8::SnapshotCreator snapshot;
v8::Isolate *isolate = snapshot.GetIsolate();
{
v8::Isolate::Scope isolate_scope(isolate);
// Create a stack-allocated handle scope.
v8::HandleScope handle_scope(isolate);
// Create a new context.
v8::Local<v8::Context> context = v8::Context::New(isolate);
// Enter the context for compiling and running the script.
v8::Context::Scope context_scope(context);
// Create a string containing the JavaScript source code.
v8::Local<v8::String> source = v8::String::NewFromUtf8(
isolate, source_code, v8::NewStringType::kNormal).ToLocalChecked();
// Compile the source code.
v8::Local<v8::Script> script = v8::Script::Compile(
context, source).ToLocalChecked();
// Run the script to get the result.
v8::Local<v8::Value> result = script->Run(context).ToLocalChecked();
// Convert the result to an UTF8 string and print it.
v8::String::Utf8Value utf8(isolate, result);
printf("%s\n", *utf8);
snapshot.SetDefaultContext(context);
}
v8::StartupData startupDataBlob = snapshot.CreateBlob(
v8::SnapshotCreator::FunctionCodeHandling::kKeep);
/*writeBinaryFile(
"/path_to_write/snapshot.bin",
startupDataBlob.raw_size,
startupDataBlob.data);*/
// Dispose the isolate and tear down V8.
isolate->Dispose();
v8::V8::Dispose();
v8::V8::ShutdownPlatform();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment