V8世界探险 (1) - v8 API概览

V8世界探险 (1) - v8 API概览

v8是Google开发的JavaScript引擎,自推出后就对js生态产生了巨大的影响。比如产生了运行在服务端的Node.js的巨大生态。

这么好玩的东西,我们当然要冲起去看看它的内部是如何实现的了。

Hello,v8 World!

首先好玩的一点是,v8可以作为一个库来嵌入到其它的应用中。

我们废话不多说,直接上代码.这是Google官方的调用在代码中嵌入一个v8引擎的例子,地址在:https://chromium.googlesource.com/v8/v8/+/branch-heads/4.8/samples/hello-world.cc

// Copyright 2015 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include 
#include 
#include 
#include "include/libplatform/libplatform.h"
#include "include/v8.h"
using namespace v8;
class ArrayBufferAllocator : public v8::ArrayBuffer::Allocator {
 public:
  virtual void* Allocate(size_t length) {
    void* data = AllocateUninitialized(length);
    return data == NULL ? data : memset(data, 0, length);
  }
  virtual void* AllocateUninitialized(size_t length) { return malloc(length); }
  virtual void Free(void* data, size_t) { free(data); }
};
int main(int argc, char* argv[]) {
  // Initialize V8.
  V8::InitializeICU();
  V8::InitializeExternalStartupData(argv[0]);
  Platform* platform = platform::CreateDefaultPlatform();
  V8::InitializePlatform(platform);
  V8::Initialize();
  // Create a new Isolate and make it the current one.
  ArrayBufferAllocator allocator;
  Isolate::CreateParams create_params;
  create_params.array_buffer_allocator = &allocator;
  Isolate* isolate = Isolate::New(create_params);
  {
    Isolate::Scope isolate_scope(isolate);
    // Create a stack-allocated handle scope.
    HandleScope handle_scope(isolate);
    // Create a new context.
    Local context = Context::New(isolate);
    // Enter the context for compiling and running the hello world script.
    Context::Scope context_scope(context);
    // Create a string containing the JavaScript source code.
    Local source =
        String::NewFromUtf8(isolate, "'Hello' + ', World!'",
                            NewStringType::kNormal).ToLocalChecked();
    // Compile the source code.
    Local
                    
                    

你可能感兴趣的:(V8世界探险 (1) - v8 API概览)