Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to parse arguments object in c++ v8

Tags:

c++

v8

I want to have access in javascript to my c++ function with google v8 engine and return result according arguments giving in my javascript function.

My javascript function is as follow:

var result = MyFc(
                 {
                  'stringData':'abc',
                  'numberData':123,
                  'arrData':[1,2,3],
                  'objData':{'a':true,'b':false,'c':true},
                  'callback':function(){}
                 }
);

I used

global->Set(v8::String::New("myFc"), v8::FunctionTemplate::New(MyFc));

v8::Handle<v8::Value> MyFc(const v8::Arguments& args) {
  obj = args[0]->...
  if( obj->stringData != 'abc' ){
      //....
  }
  if( obj->numberData != 123 ){
      //....
  }
  if( obj->arrData[2] != 3 ){
      //....
  }
  if( obj->objData->b == false ){
      //....
  }
  if( obj->callback !='abc' ){
      //....
  }
}

My question is how to parse arguments object in c++ v8? I want to access to all key values of the object in arguments, values can be an number, string, array, anonymous function or object.

like image 343
Darm Avatar asked Dec 03 '11 21:12

Darm


1 Answers

Use type checking methods of v8::Value (IsBoolean(), IsArray(), IsObject() etc) and then v8::Handle<T>::Cast(v8::Handle<S>) to cast args[i] values to corresponding types.

Your code should look like this:

if (args[0]->IsArray()) {
    Handle<Array> array = Handle<Array>::Cast(arg[0]);
    for (int i = 0; i < array->Length(); i++) {
       //...
    }
}
if (args[1]->IsObject()) {
    Handle<Object> object = Handle<Object>::Cast(args[i]);
    Handle<Value> fieldValue = object->Get(String::New("a"));
    Handle<Value> callback = object->Get(String::New("callback"));
    if (callback->IsFunction()) {
        Handle<Function> fn = Handle<Function>::Cast(callback);
    }
}
like image 185
ezhi Avatar answered Sep 22 '22 16:09

ezhi