Converting from v8::Arguments to C++ Types

mellowsoon picture mellowsoon · Sep 19, 2011 · Viewed 24.9k times · Source

I'm playing with creating Node.js modules in C++, but I'm stumped on the v8::Arguments class. Lets say I have a Javascript class for sending emails, which has a method with this signature:

Mailer::sendEmail(Array recipients, String sender, String message);

Which would be called like this:

mailer.sendEmail(["[email protected]", "[email protected]"], "[email protected]", "Hi there");

Now in C++ land, I have a class function with this signature:

SendEmail(const v8::Arguments& args)

Which is backing my Mailer::sendEmail method in Javascript land. The SendEmail function will create a new instance of my Emailer class, which itself has a class function with this signature:

send(std::list<std::string> recipients, std::string from, std::string message)

And this is where I'm lost. I don't know how to take the values from args, and convert them into regular C++ types, so I can pass the values to my send function. As I understand it, the 3 values passed to Mailer::sendEmail will be available in args[0], args[1], and args[2]. I even understand I can do some type checking like if (!args[0]->IsArray()), but actually converting args[0] to std::list<std::string> is what I don't know how to do.

Edit: I found a hackish way of doing this, but I still think V8 has some built in methods to handle this in a cleaner way.

static Handle<Value> SendEmail(const Arguments& args)
{
    HandleScope scope;

    list<string> values;
    Local<Object> obj = args[0]->ToObject();
    Local<Array> props = obj->GetPropertyNames();

    // Iterate through args[0], adding each element to our list
    for(unsigned int i = 0; i < props->Length(); i++) {
        String::AsciiValue val(obj->Get(i)->ToString());
        values.push_front(string(*val));
    }

    // Display the values in the list for debugging purposes
    for (list<string>::iterator it = values.begin(); it != values.end(); it++) {
        cout << *it << endl;
    }

    return scope.Close(args.This());
}

Answer

Ryan picture Ryan · Apr 21, 2012

I know this is an older topic, but the way I tend to do this is as follows:

Handle<Value> MethodName (const Arguments& args) {

    // get the param
    v8::String::Utf8Value param1(args[0]->ToString());

    // convert it to string
    std::string foo = std::string(*param1);    

}