[v8-users] c++ object exposed within frame's JS context

295 views
Skip to first unread message

vlad

unread,
Apr 8, 2010, 5:52:28 PM4/8/10
to v8-users
Hi,
Could somebody help me to figure out how to make c++ object available
within the frame's JS context?

Frame* frame = ...;

// Get context for the frame
v8::Local<v8::Context> context = V8Proxy::mainWorldContext(frame);

// Create v8 object v8::ObjectTemplate::New()
v8::Handle<v8::ObjectTemplate> obj = v8::ObjectTemplate::New();

// Linking passed object with the v8 object
obj->Set(v8::String::New("MyObject"), v8::ExternalWrap(MyObject));

// How to actually add the object to the context????
....

Thank you
Vlad

--
v8-users mailing list
v8-u...@googlegroups.com
http://groups.google.com/group/v8-users

Matthias Ernst

unread,
Apr 9, 2010, 2:17:44 AM4/9/10
to v8-u...@googlegroups.com
To expose a C++ object to JS, this is about what you want to do:

template = ObjectTemplate::New();
template->SetInternalFieldCount(1);
template->SetAccessor("property", Getter);

// you can actually do this many times, template acts like a class
instance = template->NewInstance();
instance->SetInternalField(0, External::Wrap(myC++Object));

context->Global()->Set("name", instance);

...

Getter(Local<String> property, const Arguments& args) {
  HandleScope locals;
  X* myC++Object =
      static_cast<X*>(External::Unwrap(args->This()->GetInternalField(0)));
  ...
  return locals.Close(result);
}

Now in JS: name.property should call your Getter.

There's some more sophisticated variations on this, e.g. using FunctionTemplate and exposing its function instance to JS, too, so you can attach JS methods to the prototype, but you should start with this.

Stephan Beal

unread,
Apr 9, 2010, 4:00:36 AM4/9/10
to v8-u...@googlegroups.com
On Fri, Apr 9, 2010 at 8:17 AM, Matthias Ernst <matt...@mernst.org> wrote:
  X* myC++Object =
      static_cast<X*>(External::Unwrap(args->This()->GetInternalField(0)));

i slight addendum to that:

be VERY careful when using GetInternalField() and Externals. Both will crash your app if they are mis-used. Always check for valid ranges, and always make sure the handle is-a External before trying to dereference it. v8 is exceedingly unforgiving of mis-use of the library (and how to use it correctly often requires a lot of guesswork, as the docs are quite lean).


--
----- stephan beal
http://wanderinghorse.net/home/stephan/

vlad

unread,
Apr 9, 2010, 8:02:08 PM4/9/10
to v8-users
THANKS!!!

On Apr 9, 1:00 am, Stephan Beal <sgb...@googlemail.com> wrote:

Reply all
Reply to author
Forward
0 new messages