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.
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}
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With