Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@xaxxon
Last active February 16, 2016 11:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xaxxon/4bd2abb161ea2253e68d to your computer and use it in GitHub Desktop.
Save xaxxon/4bd2abb161ea2253e68d to your computer and use it in GitHub Desktop.
clang++ -I/Users/xaxxon/v8 -std=c++14 -Wall -Werror bar.cpp -o bar -L/Users/xaxxon/v8/out/x64.debug/ libv8toolkit.a -lv8_base -lv8_libbase -lv8_base -lv8_libplatform -lv8_nosnapshot -licudata -licuuc -licui18n
In some_function
Allocating int at 0x7f9c12700520
uncasted internal field: 0x7f9c12700520
In some_function
Allocating int at 0x7f9c127004b0
uncasted internal field: 0x0
#include "include/libplatform/libplatform.h"
#include "include/v8.h"
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); }
};
void MyClass(const v8::FunctionCallbackInfo<v8::Value> & info) {
printf("In some_function\n");
auto js_object = info.This();
int * i = new int();
printf("Allocating int at %p\n", i);
js_object->SetInternalField(0, v8::External::New(info.GetIsolate(),i));
}
void do_something(const v8::FunctionCallbackInfo<v8::Value> & info) {
auto self = info.Holder();
auto wrap = v8::Local<v8::External>::Cast(self->GetInternalField(0));
printf("uncasted internal field: %p\n", wrap->Value());
}
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 ft = v8::FunctionTemplate::New(i, MyClass);
ft->InstanceTemplate()->SetInternalFieldCount(1);
got->Set(i, "MyClass", ft);
auto ft2 = v8::FunctionTemplate::New(i, do_something);
ft->InstanceTemplate()->Set(i, "do_something", ft2);
auto c = v8::Context::New(i, nullptr, got);
v8::Context::Scope cs(c);
auto s = v8::Script::Compile(c, v8::String::NewFromUtf8(i,"new MyClass().do_something(); Object.create(new MyClass()).do_something();")).ToLocalChecked();
(void)s->Run(c);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment