Skip to content

Instantly share code, notes, and snippets.

@fiddlerwoaroof
Created July 11, 2013 04:31
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 fiddlerwoaroof/5972548 to your computer and use it in GitHub Desktop.
Save fiddlerwoaroof/5972548 to your computer and use it in GitHub Desktop.
wrap a C++ class with V8.
#include <v8.h>
#include <iostream>
#include "utils.h"
using namespace v8;
void runJS(const std::string& inp) {
using namespace v8;
Handle<String> source = String::New( (const char*) inp.c_str() );
Handle<Script> script = Script::Compile(source);
if (script.IsEmpty()) return;
Handle<Value> result = script -> Run();
if (result.IsEmpty()) return;
String::AsciiValue ascii(result);
std::cout << *ascii << '\n';
}
class Point {
public:
Point(int x, int y) : x_(x), y_(y) {}
int x_, y_;
};
void ConstructPoint(const v8::FunctionCallbackInfo<Value>& args) {
HandleScope handle_scope;
int x = args[0]->Int32Value();
int y = args[1]->Int32Value();
Point *point = new Point(x,y);
args.This()->SetInternalField(0, External::New(point));
}
template <class T> Point* _getPoint(Local<String> name, const PropertyCallbackInfo<T>& info) {
Local<Object> self = info.Holder();
Local<External> wrap = Local<External>::Cast(self->GetInternalField(0));
void* ptr = wrap->Value();
return static_cast<Point*>(ptr);
}
void GetPointX(Local<String> name, const PropertyCallbackInfo<Value>& info) {
int value = _getPoint<Value>(name, info)->x_;
info.GetReturnValue().Set(Number::New(value));
}
void SetPointX(Local<String> name, Local<Value> value, const PropertyCallbackInfo<void>& info) {
Point* pt= _getPoint<void>(name, info);
pt->x_ = value->Int32Value();
}
void GetPointY(Local<String> name, const PropertyCallbackInfo<Value>& info) {
int value = _getPoint<Value>(name, info)->y_;
info.GetReturnValue().Set(Number::New(value));
}
void SetPointY(Local<String> name, Local<Value> value, const PropertyCallbackInfo<void>& info) {
Point* pt= _getPoint<void>(name, info);
pt->y_ = value->Int32Value();
}
int main(int argc, char* argv[]) {
Isolate* isolate = Isolate::GetCurrent();
HandleScope handle_scope(isolate);
Local<Context> context = Context::New(isolate);
Context::Scope context_scope = Context::Scope(context);
Local<FunctionTemplate> constructor = FunctionTemplate::New(ConstructPoint);
constructor->InstanceTemplate()->SetInternalFieldCount(1);
constructor->InstanceTemplate()->SetAccessor(String::New("x"), GetPointX, SetPointX);
constructor->InstanceTemplate()->SetAccessor(String::New("y"), GetPointY, SetPointY);
context->Global()->Set(String::New("Point"), constructor->GetFunction());
getInput("> ", runJS);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment