1 // Copyright 2015 the V8 project authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 #include <stdio.h> 6 #include <stdlib.h> 7 #include <string.h> 8 9 #include "include/libplatform/libplatform.h" 10 #include "include/v8.h" 11 12 using namespace v8; 13 14 class ArrayBufferAllocator : public v8::ArrayBuffer::Allocator { 15 public: 16 virtual void* Allocate(size_t length) { 17 void* data = AllocateUninitialized(length); 18 return data == NULL ? data : memset(data, 0, length); 19 } 20 virtual void* AllocateUninitialized(size_t length) { return malloc(length); } 21 virtual void Free(void* data, size_t) { free(data); } 22 }; 23 24 25 int main(int argc, char* argv[]) { 26 // Initialize V8. 27 V8::InitializeICU(); 28 V8::InitializeExternalStartupData(argv[0]); 29 Platform* platform = platform::CreateDefaultPlatform(); 30 V8::InitializePlatform(platform); 31 V8::Initialize(); 32 33 // Create a new Isolate and make it the current one. 34 ArrayBufferAllocator allocator; 35 Isolate::CreateParams create_params; 36 create_params.array_buffer_allocator = &allocator; 37 Isolate* isolate = Isolate::New(create_params); 38 { 39 Isolate::Scope isolate_scope(isolate); 40 41 // Create a stack-allocated handle scope. 42 HandleScope handle_scope(isolate); 43 44 // Create a new context. 45 Local<Context> context = Context::New(isolate); 46 47 // Enter the context for compiling and running the hello world script. 48 Context::Scope context_scope(context); 49 50 // Create a string containing the JavaScript source code. 51 Local<String> source = 52 String::NewFromUtf8(isolate, "'Hello' + ', World!'", 53 NewStringType::kNormal).ToLocalChecked(); 54 55 // Compile the source code. 56 Local<Script> script = Script::Compile(context, source).ToLocalChecked(); 57 58 // Run the script to get the result. 59 Local<Value> result = script->Run(context).ToLocalChecked(); 60 61 // Convert the result to an UTF8 string and print it. 62 String::Utf8Value utf8(result); 63 printf("%s\n", *utf8); 64 } 65 66 // Dispose the isolate and tear down V8. 67 isolate->Dispose(); 68 V8::Dispose(); 69 V8::ShutdownPlatform(); 70 delete platform; 71 return 0; 72 } 73