codeboost / bea

Expose your C++ Libraries to Javascript with Google's V8
20 stars 4 forks source link

Trouble with ToJS #3

Closed colormotor closed 12 years ago

colormotor commented 12 years ago

I can't get this to work... for example if in the example Item class, I add a copy constructor, and define a function Item duplicate() { return Item(*this); }

and call javascript code like this: var v1 = new Item("hello"); var v2 = v1.duplicate() something goes wrong, and I get an exception when the javascript constructor is called.

Am I doing something wrong here?

colormotor commented 12 years ago

turns out that the 'Is' function won't work because the value is an external... I could make it work in a hacky way by adding this to the bea generated constructor

            if( args[0]->IsExternal() )
    {
        hello::Item* t = (hello::Item*)v8::External::Unwrap(args[0]);
        hello::Item* fnRetVal = new jcm::_D_Item(*t);
        return v8::External::New(fnRetVal);
    }
colormotor commented 12 years ago

The issue is solved by uncommenting :

if (args[0]->IsExternal()) ext = v8::Handle::Cast(args[0]);

In ExposedClass::createNew, will this cause other kind of problems?

codeboost commented 12 years ago

Frankly, I cannot remember why this was commented out, but it seems to do the right thing, since the alternative is to call the constructor (again) and create (yet another) object through the copy constructor, which is unnecessary, because the new copy was created in duplicate() itself.

An alternative would be to create the duplicate() function in javascript:

Item.prototype.clone = function(){
    return new Item(this);
}

For this to work, you have to expose the copy constructor in the .bea file:

Item(const Item& other)

I've added these 'tests' to the test.js (created function clone()).

Let's try this: I'll check it in uncommented and revisit it if it causes problems. I'm still in the process of recollecting the whole architecture and v8 API so I'll figure it out soon ;).