Hi all,

I'm experimenting with V8 for scripting in a game engine. However, I'm
having trouble returning member objects of C++ classes by reference.
For example, let's say I have the following C++ classes (trimmed for
simplicity):

class Vector
{
public:
  int X;
  int Y;
};

class Sprite
{
public:
  Vector Position;
};

After wrapping these, I add a few Sprite objects to the global object
(eg: Sprite_1, Sprite_2, etc.). In Javascript, I'd like to manipulate
their positions, like so:

Sprite_1.Position.X = 32;

However, this doesn't work (ie: the sprite's position remains the
same), but this does:

Sprite_1.Position = new Vector(32,0); // Sprite position is correctly
updated

The reason the former doesn't work is because my 'GetPosition'
accessor for the Sprite class will create a *new* Vector object and
return that. In other words, the accessor will create a new (weak)
persistent handle and wrap it around the external data. This
essentially returns the vector as a value instead of a reference. I'd
like to return it as a reference, since that would be the expected
behavior. However, I'm not sure how I would go about doing that.

My code looks something like this:

Handle<Value> GetPosition( Handle<String>, const AccessorInfo& info )
{
  Local<Object> obj = info.This();
  Local<External> wrap = Local<External>::Cast( obj-
>GetInternalField(0) );
  Vector pos = static_cast<Sprite*>( wrap->Value() )->Position();
  Vector* v = new Vector(pos);

  HandleScope handle_scope;
  Handle<Object> instance = VectorTemplate->InstanceTemplate()-
>NewInstance(); // VectorTemplate is defined elsewhere
  Persistent<External> weak =
Persistent<External>::New( External::New(v) );
  weak.MakeWeak( v, Vector_Dispose );
  instance->SetInternalField(0,weak);

  return handle_scope.Close(instance);
}

I was thinking that instead of creating a new Vector, I could just
wrap a local handle around the Sprite's Position member. I'm guessing
that a persistent handle shouldn't be necessary since the lifetime of
the member object is coupled with the parent Sprite.

Does anyone have any thoughts on this? I'm still getting used to V8's
concepts...

Thanks,
Dave

-- 
v8-users mailing list
[email protected]
http://groups.google.com/group/v8-users

Reply via email to