Skip to content

Instantly share code, notes, and snippets.

@xaxxon
Created February 23, 2016 18:50
Show Gist options
  • Save xaxxon/ad74e6a9c8ab76e3faf7 to your computer and use it in GitHub Desktop.
Save xaxxon/ad74e6a9c8ab76e3faf7 to your computer and use it in GitHub Desktop.
#include <string.h>
#include <stdlib.h>
#include "include/libplatform/libplatform.h"
#include "include/v8.h"
using namespace v8;
class ArrayBufferAllocator : public v8::ArrayBuffer::Allocator {
public:
inline virtual void* Allocate(size_t length) override {
void* data = AllocateUninitialized(length);
return data == NULL ? data : memset(data, 0, length);
}
inline virtual void* AllocateUninitialized(size_t length) override { return malloc(length); }
inline virtual void Free(void* data, size_t) override { free(data); }
};
int main(int argc, char ** argv)
{
v8::V8::InitializeICU();
auto platform = v8::platform::CreateDefaultPlatform();
v8::V8::InitializePlatform(platform);
v8::V8::Initialize();
v8::Isolate::CreateParams create_params;
create_params.array_buffer_allocator = (v8::ArrayBuffer::Allocator *) new ArrayBufferAllocator();
auto i = v8::Isolate::New(create_params);
{
v8::Isolate::Scope is(i);
v8::HandleScope hs(i);
auto got = v8::ObjectTemplate::New(i);
auto c = v8::Context::New(i, nullptr, got);
{
v8::Context::Scope cs(c);
auto s = v8::Script::Compile(c, v8::String::NewFromUtf8(i,"a=function(){return b;}")).ToLocalChecked();
(void)s->Run(c);
}
// THIS WORKS
//(void)c->Global()->Set(c,String::NewFromUtf8(i,"b"), String::NewFromUtf8(i,"HELLO"));
//auto a_val = c->Global()->Get(c, String::NewFromUtf8(i,"a")).ToLocalChecked();
//auto a_func = Local<Function>::Cast(a_val);
//auto result = a_func->Call(c, c->Global(), 0, nullptr);
//printf("result: %s\n", *String::Utf8Value(result.ToLocalChecked()));
auto c2 = v8::Context::New(i, nullptr, got);
{
Context::Scope cs2(c2);
(void)c2->Global()->Set(c2,String::NewFromUtf8(i,"b"), String::NewFromUtf8(i,"HELLO"));
auto a_val2 = c2->Global()->Get(c, String::NewFromUtf8(i,"a")).ToLocalChecked();
auto a_func2 = Local<Function>::Cast(a_val2);
auto result2 = a_func2->Call(c2, c2->Global(), 0, nullptr);
printf("result: %s\n", *String::Utf8Value(result2.ToLocalChecked()));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment