4

When a C++ object that is exposed to v8 is deleted, how can I invalidate handles that may pointed to this object.

I'm using v8 as a scripting interface to a larger application. Objects in the larger application are wrapped and accessed in v8 using node's ObjectWrap class.

The issue is, the lifetime of the wrapped objects is limited. If, in javascript, I execute something like:

var win = app.getWindow();
win.close(); // The C++ object that win references goes away
console.log(win.width()); // This should fail.

I want it to behave just like the comments say. After win.close() (or some other event maybe outside JS control), any access to win or duplicated handle needs to fail.

Currently, I have to mark the wrapped C++ object to be invalid and check the validity on every method call. Is this the only way to do it, or is there a way to mark a handle as no longer valid?

aughey
  • 458
  • 3
  • 8

1 Answers1

1

The only way that comes to mind would be to have an extra function around that give an error when called. Then when you call '.close', you could create properties on your win that would take precedence over the object prototype versions.

function closedError() {
  return new Error("Window Closed");
}

win.close = function() {
  this.width = closedError;
  this.otherfunc = closedError;
};

I don't have a compiler handy at the moment, but I imagine something like this in C++.

static Handle<Value> Close(const Arguments& args) {
  HandleScope scope;
  NODE_SET_METHOD(args.This(), "width", Window::Width);
  NODE_SET_METHOD(args.This(), "otherfunc", Window::OtherFunc);
}
loganfsmyth
  • 156,129
  • 30
  • 331
  • 251
  • Interesting possible solution. One could easily write a function that would "destroy" a handle by setting all of the methods to an error method. – aughey Feb 29 '12 at 05:21
  • It seems less complex that checking in every function. That said, if you made a macro, it'd also be pretty easy to stick a check at the top of every function. – loganfsmyth Feb 29 '12 at 05:40