Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to return a struct from V8 C++ function to javascript module

I am new to Javascript and V8 library. My requirement is call a C++ function and return a C struct back to Javascript module.

struct empDetails {
    int empNo;
    string empName;
};

v8::Handle<v8::Value> getDetails(const v8::Arguments &args) {
    if ((args.Length() != 1) || !args[0]->IsUint32()) {
        return v8::ThrowException(v8::Exception::Error    
                (v8::String::New("Invalid> arguments.")));
    }
    uint32_t userId = args[0]->ToUint32()->Value();
    empDetails e;
    company::GetEmpdetails(userId, e); // other static function in my project
    return e;
}

At return statement, I am getting error. Could anyone tell me how to return a struct from V8 C++ function.

like image 485
coder Avatar asked Nov 01 '12 15:11

coder


2 Answers

You want to create Javascript object and populate every member of it with your data.

#define function(name) v8::Handle<v8::Value> name(const v8::Arguments& a)

    function (example_object) {
        v8::HandleScope handle_scope;
        Handle<Object> Result = Object::New();
        Result->Set(String::New("name"), String::New("Stackoverflow"));
        Result->Set(String::New("url"), String::New("http://stackoverflow.com"));
        Result->Set(String::New("javascript_tagged"), Number::New(317566));
        return handle_scope.Close(Result);
    }

Call from Javascript:

log(JSON.stringify(example_object()))

Output

{"name":"Stackoverflow","url":"http://stackoverflow.com","javascript_tagged":317566}
like image 166
exebook Avatar answered Nov 04 '22 16:11

exebook


When you want to create node.js module,

npm install ref
npm install ref-array
npm install ref-struct

in your js source:

var ref = require('ref');
var ArrayType = require('ref-array')
var StructType = require('ref-struct');
var empDetails = StructType({
    empNo: ref.types.int,
    empName: ArrayType('char', STRING_LENGTH)
});
var result = new empDetails;
getDetails(999, result.ref());

in your module source:

struct empDetails {
    int empNo;
    char empName[STRING_LENGTH];
};
v8::Handle<v8::Value> getDetails(const v8::Arguments &args) {
    if((args.Length() != 2) || !args[0]->IsUint32()){
        return v8::ThrowException(v8::Exception::Error    
            (v8::String::New("Invalid> arguments.")));
    }
    uint32_t userId = args[0]->ToUint32()->Value();
    struct empDetails src;
    company::GetEmpdetails(userId, src);
    v8::Handle<v8::Object> dst = args[1]->ToObject();
    if(node::Buffer::Length(dst) >= sizeof(struct empDetails))
        memcpy(node::Buffer::Data(dst), &src, sizeof(struct empDetails));
    return args.This();
}
like image 34
idobatter Avatar answered Nov 04 '22 16:11

idobatter