本文整理汇总了C++中Local类的典型用法代码示例。如果您正苦于以下问题:C++ Local类的具体用法?C++ Local怎么用?C++ Local使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Local类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: getdns_dict_create
getdns_dict* GNUtil::convertToDict(Local<Object> obj) {
if (obj->IsRegExp() || obj->IsDate() ||
obj->IsFunction() || obj->IsUndefined() ||
obj->IsNull() || obj->IsArray()) {
return NULL;
}
Local<Array> names = obj->GetOwnPropertyNames();
getdns_dict* result = getdns_dict_create();
for(unsigned int i = 0; i < names->Length(); i++) {
Local<Value> nameVal = names->Get(i);
Nan::Utf8String name(nameVal);
Local<Value> val = obj->Get(nameVal);
GetdnsType type = getGetdnsType(val);
switch (type) {
case IntType:
getdns_dict_set_int(result, *name, val->ToUint32()->Value());
break;
case BoolType:
if (val->IsTrue()) {
getdns_dict_set_int(result, *name, GETDNS_EXTENSION_TRUE);
} else {
getdns_dict_set_int(result, *name, GETDNS_EXTENSION_FALSE);
}
break;
case StringType:
{
struct getdns_bindata strdata;
String::Utf8Value utf8Str(val->ToString());
int len = utf8Str.length();
strdata.data = (uint8_t*) *utf8Str;
strdata.size = len;
getdns_dict_set_bindata(result, *name, &strdata);
}
break;
case BinDataType:
{
struct getdns_bindata bdata;
bdata.data = (uint8_t*) node::Buffer::Data(val);
bdata.size = node::Buffer::Length(val);
getdns_dict_set_bindata(result, *name, &bdata);
}
break;
case ListType:
{
Local<Array> subArray = Local<Array>::Cast(val);
struct getdns_list* sublist = GNUtil::convertToList(subArray);
getdns_dict_set_list(result, *name, sublist);
getdns_list_destroy(sublist);
}
break;
case DictType:
{
Local<Object> subObj = val->ToObject();
struct getdns_dict* subdict = GNUtil::convertToDict(subObj);
if (subdict) {
getdns_dict_set_dict(result, *name, subdict);
getdns_dict_destroy(subdict);
}
}
break;
default:
break;
}
}
return result;
}
示例2: getQuote
/*
* Wrap the quote() method to marshal and unmarshal arguments
*
* Entirely inefficient.
*
* Will throw an exception if the Quote fails.
* Currently doing NO INPUT VALIDATION
*
* Arguments: srkpwd, aikfile, pcrs[], nonce
*
*/
static Handle<Value> getQuote(const Arguments& args) {
//unmarshal the arguments
Local<String> srkpwd = args[0]->ToString();
Local<String> aik = args[1]->ToString();
Local<Object> pcrsObj = args[2]->ToObject();
Local<Object> nonceObj = args[3]->ToObject();
int fieldCount = 0;
while (pcrsObj->Has(fieldCount))
fieldCount++;
long pcrs[fieldCount];
int i = 0;
for (i = 0; i < fieldCount; i++) {
pcrs[i] = pcrsObj->Get(i)->Int32Value();
}
int j = 0;
BYTE nonce[20];
while (nonceObj->Has(j) && j < 20) {
nonce[j] = nonceObj->Get(j)->Int32Value();
j++;
}
char* srkpwdAscii = stringToChar(srkpwd);
char* aikAscii = stringToChar(aik);
TSS_VALIDATION valid;
TPM_QUOTE_INFO quoteInfo;
//perform the quote
TSS_RESULT quoteRes = quote(srkpwdAscii, aikAscii, pcrs, fieldCount, nonce,
&valid, "eInfo);
if (quoteRes != 0) {
return ThrowException(
Exception::Error(String::New("Error producing TPM Quote")));
}
// turn all these stupid TSS structs into JSON structures!
Local<Object> validData = Object::New();
validData->Set(String::New("rgbData"),
bytesToArray(valid.rgbData, valid.ulDataLength));
validData->Set(String::New("rgbExternalData"),
bytesToArray(valid.rgbExternalData, valid.ulExternalDataLength));
validData->Set(String::New("rgbValidationData"),
bytesToArray(valid.rgbValidationData, valid.ulValidationDataLength));
validData->Set(String::New("versionInfo"),
version2ToObject(valid.versionInfo));
Local<Object> quoteData = Object::New();
quoteData->Set(String::New("compositeHash"),
bytesToArray(quoteInfo.compositeHash.digest, 20));
quoteData->Set(String::New("externalData"),
bytesToArray(quoteInfo.externalData.nonce, 20));
quoteData->Set(String::New("fixed"), bytesToArray(quoteInfo.fixed, 4));
quoteData->Set(String::New("versionInfo"),
versionToObject(quoteInfo.version));
Local<Object> both = Object::New();
both->Set(String::New("validationData"), validData);
both->Set(String::New("quoteInfo"), quoteData);
free(aikAscii);
free(srkpwdAscii);
return both;
}
示例3:
Handle<Object> HoneydNodeJs::WrapProfile(NodeProfile *pfile)
{
HandleScope scope;
// Setup the template for the type if it hasn't been already
if( m_profileTemplate.IsEmpty() )
{
Handle<FunctionTemplate> nodeTemplate = FunctionTemplate::New();
nodeTemplate->InstanceTemplate()->SetInternalFieldCount(1);
m_profileTemplate = Persistent<FunctionTemplate>::New(nodeTemplate);
// Javascript methods
Local<Template> proto = m_profileTemplate->PrototypeTemplate();
proto->Set("GetName", FunctionTemplate::New(InvokeMethod<std::string, NodeProfile, &Nova::NodeProfile::GetName>));
proto->Set("GetPortNames", FunctionTemplate::New(InvokeMethod<std::vector<std::string>, NodeProfile, &Nova::NodeProfile::GetPortNames>));
proto->Set("GetTcpAction", FunctionTemplate::New(InvokeMethod<std::string, NodeProfile, &Nova::NodeProfile::GetTcpAction>));
proto->Set("GetUdpAction", FunctionTemplate::New(InvokeMethod<std::string, NodeProfile, &Nova::NodeProfile::GetUdpAction>));
proto->Set("GetIcmpAction", FunctionTemplate::New(InvokeMethod<std::string, NodeProfile, &Nova::NodeProfile::GetIcmpAction>));
proto->Set("GetPersonality", FunctionTemplate::New(InvokeMethod<std::string, NodeProfile, &Nova::NodeProfile::GetPersonality>));
proto->Set("GetEthernet", FunctionTemplate::New(InvokeMethod<std::string, NodeProfile, &Nova::NodeProfile::GetEthernet>));
proto->Set("GetUptimeMin", FunctionTemplate::New(InvokeMethod<std::string, NodeProfile, &Nova::NodeProfile::GetUptimeMin>));
proto->Set("GetUptimeMax", FunctionTemplate::New(InvokeMethod<std::string, NodeProfile, &Nova::NodeProfile::GetUptimeMax>));
proto->Set("GetDropRate", FunctionTemplate::New(InvokeMethod<std::string, NodeProfile, &Nova::NodeProfile::GetDropRate>));
proto->Set("GetGenerated", FunctionTemplate::New(InvokeMethod<bool, NodeProfile, &Nova::NodeProfile::GetGenerated>));
proto->Set("GetDistribution", FunctionTemplate::New(InvokeMethod<double, NodeProfile, &Nova::NodeProfile::GetDistribution>));
proto->Set("GetParentProfile", FunctionTemplate::New(InvokeMethod<std::string, NodeProfile, &Nova::NodeProfile::GetParentProfile>));
proto->Set("GetVendors", FunctionTemplate::New(InvokeMethod<std::vector<std::string>, NodeProfile, &Nova::NodeProfile::GetVendors>));
proto->Set("GetVendorDistributions", FunctionTemplate::New(InvokeMethod<std::vector<double>, NodeProfile, &Nova::NodeProfile::GetVendorDistributions>));
proto->Set("isTcpActionInherited", FunctionTemplate::New(InvokeMethod<bool, NodeProfile, &Nova::NodeProfile::isTcpActionInherited>));
proto->Set("isUdpActionInherited", FunctionTemplate::New(InvokeMethod<bool, NodeProfile, &Nova::NodeProfile::isUdpActionInherited>));
proto->Set("isIcmpActionInherited", FunctionTemplate::New(InvokeMethod<bool, NodeProfile, &Nova::NodeProfile::isIcmpActionInherited>));
proto->Set("isPersonalityInherited",FunctionTemplate::New(InvokeMethod<bool, NodeProfile, &Nova::NodeProfile::isPersonalityInherited>));
proto->Set("isEthernetInherited", FunctionTemplate::New(InvokeMethod<bool, NodeProfile, &Nova::NodeProfile::isEthernetInherited>));
proto->Set("isUptimeInherited", FunctionTemplate::New(InvokeMethod<bool, NodeProfile, &Nova::NodeProfile::isUptimeInherited>));
proto->Set("isDropRateInherited", FunctionTemplate::New(InvokeMethod<bool, NodeProfile, &Nova::NodeProfile::isDropRateInherited>));
}
// Get the constructor from the template
Handle<Function> ctor = m_profileTemplate->GetFunction();
// Instantiate the object with the constructor
Handle<Object> result = ctor->NewInstance();
// Wrap the native object in an handle and set it in the internal field to get at later.
Handle<External> profilePtr = External::New(pfile);
result->SetInternalField(0,profilePtr);
return scope.Close(result);
}
示例4: ThrowException
Handle<Value> Datasource::New(const Arguments& args)
{
HandleScope scope;
if (!args.IsConstructCall())
return ThrowException(String::New("Cannot call constructor as function, you need to use 'new' keyword"));
if (args[0]->IsExternal())
{
//std::clog << "external!\n";
Local<External> ext = Local<External>::Cast(args[0]);
void* ptr = ext->Value();
Datasource* d = static_cast<Datasource*>(ptr);
d->Wrap(args.This());
return args.This();
}
if (!args.Length() == 1){
return ThrowException(Exception::TypeError(
String::New("accepts only one argument, an object of key:value datasource options")));
}
if (!args[0]->IsObject())
return ThrowException(Exception::TypeError(
String::New("must provide an object, eg {type: 'shape', file : 'world.shp'}")));
Local<Object> options = args[0]->ToObject();
// TODO - maybe validate in js?
bool bind=true;
if (options->Has(String::New("bind")))
{
Local<Value> bind_opt = options->Get(String::New("bind"));
if (!bind_opt->IsBoolean())
return ThrowException(Exception::TypeError(
String::New("'bind' must be a Boolean")));
bind = bind_opt->BooleanValue();
}
mapnik::parameters params;
Local<Array> names = options->GetPropertyNames();
uint32_t i = 0;
uint32_t a_length = names->Length();
while (i < a_length) {
Local<Value> name = names->Get(i)->ToString();
Local<Value> value = options->Get(name);
params[TOSTR(name)] = TOSTR(value);
i++;
}
mapnik::datasource_ptr ds;
try
{
ds = mapnik::datasource_cache::create(params, bind);
}
catch (const mapnik::config_error & ex )
{
return ThrowException(Exception::Error(
String::New(ex.what())));
}
catch (const mapnik::datasource_exception & ex )
{
return ThrowException(Exception::Error(
String::New(ex.what())));
}
catch (const std::runtime_error & ex )
{
return ThrowException(Exception::Error(
String::New(ex.what())));
}
catch (const std::exception & ex)
{
return ThrowException(Exception::Error(
String::New(ex.what())));
}
catch (...)
{
return ThrowException(Exception::Error(
String::New("unknown exception happened, please file bug")));
}
if (ds)
{
Datasource* d = new Datasource();
d->Wrap(args.This());
d->datasource_ = ds;
return args.This();
}
return Undefined();
}
示例5: newIndexBound
Handle<Value> newIndexBound(const Arguments &args) {
HandleScope scope;
const Local<Object> spec = args[0]->ToObject();
Local<Value> v;
Local<Object> o;
NdbIndexScanOperation::IndexBound * bound =
new NdbIndexScanOperation::IndexBound;
Local<Object> jsBound = IndexBoundEnvelope.newWrapper();
wrapPointerInObject(bound, IndexBoundEnvelope, jsBound);
bound->low_key = 0;
v = spec->Get(BOUND_LOW_KEY);
if(v->IsNull()) {
bound->low_key = 0;
} else {
o = v->ToObject();
bound->low_key = node::Buffer::Data(o);
}
bound->low_key_count = 0;
v = spec->Get(BOUND_LOW_KEY_COUNT);
if(! v->IsNull()) {
bound->low_key_count = v->Uint32Value();
}
bound->low_inclusive = false;
v = spec->Get(BOUND_LOW_INCLUSIVE);
if(! v->IsNull()) {
bound->low_inclusive = v->BooleanValue();
}
bound->high_key = 0;
v = spec->Get(BOUND_HIGH_KEY);
if(v->IsNull()) {
bound->high_key = 0;
} else {
o = v->ToObject();
bound->high_key = node::Buffer::Data(o);
}
bound->high_key_count = 0;
v = spec->Get(BOUND_HIGH_KEY_COUNT);
if(! v->IsNull()) {
bound->high_key_count = v->Uint32Value();
}
bound->high_inclusive = false;
v = spec->Get(BOUND_HIGH_INCLUSIVE);
if(! v->IsNull()) {
bound->high_inclusive = v->BooleanValue();
}
bound->range_no = 0;
v = spec->Get(BOUND_RANGE_NO);
if(! v->IsNull()) {
bound->range_no = v->Uint32Value();
}
debug_print_bound(bound);
return scope.Close(jsBound);
}
示例6: ThrowException
Handle<Value> Grid::New(const Arguments& args)
{
HandleScope scope;
if (!args.IsConstructCall())
return ThrowException(String::New("Cannot call constructor as function, you need to use 'new' keyword"));
if (args[0]->IsExternal())
{
//std::clog << "external!\n";
Local<External> ext = Local<External>::Cast(args[0]);
void* ptr = ext->Value();
Grid* g = static_cast<Grid*>(ptr);
g->Wrap(args.This());
return args.This();
}
if (args.Length() >= 2)
{
if (!args[0]->IsNumber() || !args[1]->IsNumber())
return ThrowException(Exception::TypeError(
String::New("Grid 'width' and 'height' must be a integers")));
// defaults
std::string key("__id__");
unsigned int resolution = 1;
if (args.Length() >= 3) {
if (!args[2]->IsObject())
return ThrowException(Exception::TypeError(
String::New("optional third arg must be an options object")));
Local<Object> options = args[2]->ToObject();
if (options->Has(String::New("key"))) {
Local<Value> bind_opt = options->Get(String::New("key"));
if (!bind_opt->IsString())
return ThrowException(Exception::TypeError(
String::New("optional arg 'key' must be an string")));
key = TOSTR(bind_opt);
}
// TODO - remove, deprecated
if (options->Has(String::New("resolution"))) {
Local<Value> bind_opt = options->Get(String::New("resolution"));
if (!bind_opt->IsNumber())
return ThrowException(Exception::TypeError(
String::New("optional arg 'resolution' must be an string")));
resolution = bind_opt->IntegerValue();
}
}
Grid* g = new Grid(args[0]->IntegerValue(),args[1]->IntegerValue(),key,resolution);
g->Wrap(args.This());
return args.This();
}
else
{
return ThrowException(Exception::Error(
String::New("please provide Grid width and height")));
}
return Undefined();
}
示例7: getComponentType
int Conv::ToV8Sequence(JNIEnv *jniEnv, jarray jVal, int expectedType, Handle<Array> *val) {
unsigned int componentType = getComponentType(expectedType);
int length = jniEnv->GetArrayLength(jVal);
Local<Array> lVal = Local<Array>(Array::New(length));
int result = OK;
if(isJavaObject(componentType)) {
jobjectArray jOVal = (jobjectArray)jVal;
for(int i = 0; i < length; i++) {
Local<Value> elt;
jobject jElt = jniEnv->GetObjectArrayElement(jOVal, i);
result = ToV8Value(jniEnv, jElt, componentType, &elt);
jniEnv->DeleteLocalRef(jElt);
if(result != OK) break;
lVal->Set(i, elt);
}
if(result == OK) {
*val = lVal;
}
if(jniEnv->ExceptionCheck()) {
jniEnv->ExceptionClear();
result = ErrorVM;
}
return result;
}
/* FIXME: use optimised buffers */
switch(componentType) {
case TYPE_BYTE: {
jbyteArray jBVal = (jbyteArray)jVal;
jbyte *elts = jniEnv->GetByteArrayElements(jBVal, 0);
for(int i = 0; i < length; i++) {
lVal->Set(i, Number::New(elts[i]));
}
jniEnv->ReleaseByteArrayElements(jBVal, elts, 0);
}
break;
case TYPE_INT: {
jintArray jIVal = (jintArray)jVal;
jint *elts = jniEnv->GetIntArrayElements(jIVal, 0);
for(int i = 0; i < length; i++) {
lVal->Set(i, Number::New(elts[i]));
}
jniEnv->ReleaseIntArrayElements(jIVal, elts, 0);
}
break;
case TYPE_LONG: {
jlongArray jJVal = (jlongArray)jVal;
jlong *elts = jniEnv->GetLongArrayElements(jJVal, 0);
for(int i = 0; i < length; i++) {
lVal->Set(i, Number::New(elts[i]));
}
jniEnv->ReleaseLongArrayElements(jJVal, elts, 0);
}
break;
case TYPE_DOUBLE: {
jdoubleArray jDVal = (jdoubleArray)jVal;
jdouble *elts = jniEnv->GetDoubleArrayElements(jDVal, 0);
for(int i = 0; i < length; i++) {
lVal->Set(i, Number::New(elts[i]));
}
jniEnv->ReleaseDoubleArrayElements(jDVal, elts, 0);
}
break;
default:
result = ErrorType;
}
if(result == OK) {
*val = lVal;
}
if(jniEnv->ExceptionCheck()) {
jniEnv->ExceptionClear();
result = ErrorVM;
}
return result;
}
示例8: selectSync
// SELECT SYNC
void selectSync(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = Isolate::GetCurrent();
HandleScope scope(isolate);
char query[1000];
unsigned int i,limit;
int j,temp;
SQLRETURN retcode;
SQLSMALLINT colCount = 0;
SQLLEN indicator;
SQLINTEGER *intData[30];
SQLCHAR *charData[30];
SQLDOUBLE *doubleData[30];
// extract argument 1 (Query)
v8::String::Utf8Value param1(args[0]->ToString());
std::string queryRaw = std::string(*param1);
for(i=0;i<queryRaw.length();i++) query[i] = queryRaw[i]; query[i] = '\0';
//extracting SQL limit
temp = (int)args[1]->NumberValue();
if(temp < 0){
limit = 4294967294;
}
else{
limit = temp;
}
// define callback
Local<Function> cb = Local<Function>::Cast(args[2]);
// Allocate a statement handle
retcode = SQLAllocHandle(SQL_HANDLE_STMT, hdbc, &hstmt);
if(!SQL_SUCCEEDED(retcode)){
printf("ERROR AT ALLOCATING STATEMENT HANDLE\n");
extract_error(hstmt, SQL_HANDLE_STMT);
}
// select statement
retcode = SQLPrepare(hstmt, (SQLCHAR *)query, SQL_NTS);
if(!SQL_SUCCEEDED(retcode)){
printf("ERROR AT SQLPREPARE\n");
extract_error(hstmt, SQL_HANDLE_STMT);
}
Column* columns = GetColumns(&colCount);
for(j=0;j<colCount;j++) {
if(columns[j].type == SQL_C_LONG) {
intData[j] = (SQLINTEGER *) malloc (columns[j].size+1);
retcode = SQLBindCol(hstmt, columns[j].index, columns[j].type, intData[j], columns[j].size, &indicator);
}
else if(columns[j].type == SQL_C_DOUBLE) {
doubleData[j] = (SQLDOUBLE *) malloc (columns[j].size+1);
retcode = SQLBindCol(hstmt, columns[j].index, columns[j].type, doubleData[j], columns[j].size, &indicator);
}
else if(columns[j].type == SQL_C_CHAR) {
charData[j] = (SQLCHAR *) malloc (columns[j].size+1);
retcode = SQLBindCol(hstmt, columns[j].index, columns[j].type, charData[j], columns[j].size, &indicator);
}
if(!SQL_SUCCEEDED(retcode)){
printf("ERROR AT BINDING COLUMNS\n");
extract_error(hstmt, SQL_HANDLE_STMT);
break;
}
}
// Execute the statement handle
retcode = SQLExecute (hstmt);
if(!SQL_SUCCEEDED(retcode)){
printf("ERROR AT SQLEXECUTE\n");
extract_error(hstmt, SQL_HANDLE_STMT);
}
// Array of Records
Local<Array> result = Array::New(isolate);
Local<Object> obj;
// Fetch and print each row of data until SQL_NO_DATA returned.
for(i=0;i<limit; i++) {
retcode = SQLFetch(hstmt);
if (retcode == SQL_NO_DATA) {
break;
}
if(!SQL_SUCCEEDED(retcode)){
printf("ERROR AT SQLFETCH\n");
extract_error(hstmt, SQL_HANDLE_STMT);
break;
}
// Retrieve individual Records and store in the object
obj = Object::New(isolate);
for(j=0;j<colCount;j++) {
if (columns[j].type == SQL_C_LONG) {
obj->Set(String::NewFromUtf8(isolate, (char *) columns[j].name), Number::New(isolate, (long) *intData[j]));
//.........这里部分代码省略.........
示例9: SetProtocol
// notification.protocol=
static void SetProtocol(Local<String> property, Local<Value> value, const AccessorInfo& info) {
RCSwitchNode* rcswitchNode_instance = node::ObjectWrap::Unwrap<RCSwitchNode>(info.Holder());
if(value->IsInt32())
rcswitchNode_instance->rcswitch.setProtocol(value->Int32Value());
}
示例10: assert
void ObjectManager::MarkReachableObjects(Isolate *isolate, const Local<Object>& obj)
{
stack< Local<Value> > s;
s.push(obj);
auto propName = String::NewFromUtf8(isolate, "t::gcNum");
assert(!m_markedForGC.empty());
auto& topGCInfo = m_markedForGC.top();
int numberOfGC = topGCInfo.numberOfGC;
auto curGCNumValue = Integer::New(isolate, numberOfGC);
while (!s.empty())
{
auto top = s.top();
s.pop();
if (top.IsEmpty() || !top->IsObject())
{
continue;
}
auto o = top.As<Object>();
uint8_t *addr = NativeScriptExtension::GetAddress(o);
auto itFound = m_visited.find(addr);
if (itFound != m_visited.end())
{
continue;
}
m_visited.insert(addr);
if (o->IsFunction())
{
auto func = o.As<Function>();
int closureObjectLength;
auto closureObjects = NativeScriptExtension::GetClosureObjects(isolate, func, &closureObjectLength);
for (int i=0; i<closureObjectLength; i++)
{
auto& curV = *(closureObjects + i);
if (!curV.IsEmpty() && curV->IsObject())
{
s.push(curV);
}
}
NativeScriptExtension::ReleaseClosureObjects(closureObjects);
}
auto jsInfo = GetJSInstanceInfo(o);
if (jsInfo != nullptr)
{
o->SetHiddenValue(propName, curGCNumValue);
}
auto proto = o->GetPrototype();
if (!proto.IsEmpty() && !proto->IsNull() && !proto->IsUndefined() && proto->IsObject())
{
s.push(proto);
}
auto context = isolate->GetCurrentContext();
bool success = false;
auto propNames = NativeScriptExtension::GetPropertyKeys(isolate, context, o, success);
assert(success);
int len = propNames->Length();
for (int i = 0; i < len; i++)
{
auto propName = propNames->Get(i);
if (propName->IsString())
{
auto name = propName.As<String>();
bool isPropDescriptor = o->HasRealNamedCallbackProperty(name);
if (isPropDescriptor)
{
Local<Value> getter;
Local<Value> setter;
NativeScriptExtension::GetAssessorPair(isolate, o, name, getter, setter);
if (!getter.IsEmpty() && getter->IsFunction())
{
int getterClosureObjectLength = 0;
auto getterClosureObjects = NativeScriptExtension::GetClosureObjects(isolate, getter.As<Function>(), &getterClosureObjectLength);
for (int i=0; i<getterClosureObjectLength; i++)
{
auto& curV = *(getterClosureObjects + i);
if (!curV.IsEmpty() && curV->IsObject())
{
s.push(curV);
}
}
NativeScriptExtension::ReleaseClosureObjects(getterClosureObjects);
}
if (!setter.IsEmpty() && setter->IsFunction())
{
int setterClosureObjectLength = 0;
//.........这里部分代码省略.........
示例11: Undefined
/**
* @details This is set by `MapservAsync` to run after `MapservWork` has
* finished, being passed the response generated by the latter and running in
* the same thread as the former. It formats the mapserv response into
* javascript datatypes and returns them via the original callback.
*
* @param req The asynchronous libuv request.
*/
void Map::MapservAfter(uv_work_t *req) {
HandleScope scope;
MapBaton *baton = static_cast<MapBaton*>(req->data);
Map *self = baton->self;
gdBuffer *buffer = baton->buffer;
Handle<Value> argv[2];
if (baton->error) {
argv[0] = baton->error->toV8Error();
delete baton->error; // we've finished with it
} else {
argv[0] = Undefined();
}
// convert the http_response to a javascript object
Local<Object> result = Object::New();
// Add the content-type to the headers object. This object mirrors the
// HTTP headers structure and creates an API that allows for the addition
// of other headers in the future.
Local<Object> headers = Object::New();
if (baton->content_type) {
Local<Array> values = Array::New(1);
values->Set(0, String::New(baton->content_type));
headers->Set(String::New("Content-Type"), values);
}
result->Set(headers_symbol, headers);
// set the response data as a Node Buffer object. This is zero-copied from
// mapserver and free'd when the buffer is garbage collected.
if (buffer && buffer->data) {
result->Set(data_symbol,
Buffer::New((char *)buffer->data, buffer->size, FreeBuffer, NULL)->handle_);
// add the content-length header
Local<Array> values = Array::New(1);
values->Set(0, Uint32::New(buffer->size));
headers->Set(String::New("Content-Length"), values);
}
argv[1] = result;
// pass the results to the user specified callback function
TryCatch try_catch;
baton->callback->Call(Context::GetCurrent()->Global(), 2, argv);
if (try_catch.HasCaught()) {
FatalException(try_catch);
}
// clean up
if (buffer) {
delete baton->buffer;
baton->buffer = NULL;
}
if (baton->content_type) {
msFree(baton->content_type);
}
baton->env.clear();
baton->callback.Dispose();
self->Unref(); // decrement the map reference so it can be garbage collected
delete baton;
return;
}
示例12: ThrowException
Handle<Value> Pngquant::Compress(const Arguments& args) {
HandleScope scope;
struct rwpng_data * out_buffer;
struct rwpng_data * in_buffer;
if (args.Length() != 3) {
return ThrowException(Exception::TypeError(
String::New("Invalid argument, Need three arguments!")
)
);
}
if (!Buffer::HasInstance(args[0])) {
return ThrowException(Exception::TypeError(
String::New("First argument must be a buffer.")
)
);
}
if (!args[2]->IsFunction()) {
return ThrowException(Exception::TypeError(
String::New("Third argument must be a callback function.")
)
);
}
png_bytep in_stream = (png_bytep) Buffer::Data(args[0]->ToObject());
unsigned in_length = Buffer::Length(args[0]->ToObject());
Local<String> opt = args[1]->ToString();
Local<Function> callback = Local<Function>::Cast(args[2]);
Buffer *buffer;
char str_buffer[BUFFER_SIZE];
memset(str_buffer, '\0', BUFFER_SIZE);
opt->WriteUtf8(str_buffer);
char *argv[32] = {""};
char token[BUFFER_SIZE];
memset(token, '\0', BUFFER_SIZE);
int i = 0, argc = 0, k = 0, len = 0;
while(str_buffer[i] != '\0') {
if (argc >= 30) {
break;
}
if (str_buffer[i] == ' ') {
argc++;
k = 0;
len = strlen(token);
argv[argc] = (char*) malloc(len + 1);
memset(argv[argc], '\0', len + 1);
memcpy(argv[argc], token, len + 1);
//reset token
memset(token, '\0', BUFFER_SIZE);
} else {
token[k++] = str_buffer[i];
}
i++;
}
argv[0] = "pngquant";
if ((len = strlen(token)) > 0) {
argc++;
argv[argc] = (char*) malloc(len + 1);
memset(argv[argc], '\0', len + 1);
memcpy(argv[argc], token, len + 1);
argc = argc + 1; //0 1 2
}
in_buffer = (struct rwpng_data *)malloc(sizeof(struct rwpng_data));
if (in_buffer == NULL) {
return ThrowException(Exception::TypeError(
String::New("malloc fail!")
)
);
}
out_buffer = (struct rwpng_data *)malloc(sizeof(struct rwpng_data));
if (out_buffer == NULL) {
return ThrowException(Exception::TypeError(
String::New("malloc fail!")
)
);
}
memset(out_buffer, '\0', sizeof(struct rwpng_data));
in_buffer->png_data = in_stream;
in_buffer->length = in_length;
in_buffer->bytes_read = 0;
int ret = pngquant(in_buffer, out_buffer, argc, argv);
if (ret != 0) {
out_buffer->png_data = in_buffer->png_data;
out_buffer->length = in_buffer->length;
fprintf(stderr, "File: %s\n", argv[argc-1]);
}
buffer = Buffer::New((char *)out_buffer->png_data, out_buffer->length);
free(in_buffer);
//.........这里部分代码省略.........
示例13: afterListImpl
void afterListImpl(Baton *baton)
{
//ESPECIFICO *********
Local<Object> responseInfo = Object::New();
responseInfo->Set(String::NewSymbol("errorStatus"), Integer::New(baton->errorStatus));
TorrentsStat *torrentsStat = baton->torrentsStat;
Handle<Array> arrayToSend = Array::New(torrentsStat->totalTorrents);
for ( int i=0; i < torrentsStat->totalTorrents; i++)
{
Local<Object> torrentInfo = Object::New();
torrentInfo->Set(String::NewSymbol("id"), Integer::New(torrentsStat->torrentStatList[i].id));
if ( torrentsStat->torrentStatList[i].error )
torrentInfo->Set(String::NewSymbol("errorMark"), String::New("*"));
else
torrentInfo->Set(String::NewSymbol("errorMark"), String::New(" "));
if ( torrentsStat->torrentStatList[i].sizeWhenDone )
{
float done = (torrentsStat->torrentStatList[i].sizeWhenDone - torrentsStat->torrentStatList[i].leftUntilDone) / torrentsStat->torrentStatList[i].sizeWhenDone;
torrentInfo->Set(String::NewSymbol("done"), String::New(tNode::Utils::folatToPercent(done).c_str()));
}
else
torrentInfo->Set(String::NewSymbol("done"), String::New("n/a"));
torrentInfo->Set(String::NewSymbol("have"), Integer::New(torrentsStat->torrentStatList[i].sizeWhenDone - torrentsStat->torrentStatList[i].leftUntilDone));
if ( torrentsStat->torrentStatList[i].leftUntilDone || torrentsStat->torrentStatList[i].eta != -1)
torrentInfo->Set(String::NewSymbol("eta"), String::New(tNode::Utils::intToString(torrentsStat->torrentStatList[i].eta).c_str()));
else
torrentInfo->Set(String::NewSymbol("eta"), String::New("Done"));
torrentInfo->Set(String::NewSymbol("up"), Number::New(torrentsStat->torrentStatList[i].rateUpload));
torrentInfo->Set(String::NewSymbol("down"), Number::New(torrentsStat->torrentStatList[i].rateDownload));
torrentInfo->Set(String::NewSymbol("ratio"), Number::New(torrentsStat->torrentStatList[i].uploadRatio));
torrentInfo->Set(String::NewSymbol("status"), String::New(transSession->getTorrentStatusString(torrentsStat->torrentStatList[i]).c_str()));
torrentInfo->Set(String::NewSymbol("name"), String::New(torrentsStat->torrentStatList[i].name));
arrayToSend->Set(i,torrentInfo);
}
delete torrentsStat->torrentStatList;
delete [] torrentsStat;
responseInfo->Set(String::NewSymbol("torrents"), arrayToSend);
const unsigned argc = 1;
Local<Value> argv[argc];
argv[0] = responseInfo;
//ESPECIFICO *********
TryCatch try_catch;
baton->callback->Call(Context::GetCurrent()->Global(), argc, argv);
baton->callback.Dispose();
delete baton;
}
示例14: mp3ToTorrent
static Handle<Value> mp3ToTorrent(const Arguments& args)
{
HandleScope scope;
if (args.Length() < 3) {
ThrowException(Exception::TypeError(String::New("Wrong number of arguments")));
return scope.Close(Undefined());
}
pthread_mutex_lock(&suscribe_mutex);
if ( !isSuscribed )
{
loop = uv_default_loop();
uv_async_init(loop, &status_change_notifier, after);
isSuscribed = false;
}
pthread_mutex_unlock(&suscribe_mutex);
Baton *baton = new Baton();
baton->errorStatus = NO_ERROR;
//ESPECIFICO *********
baton->errorStatus = NO_ERROR;
String::Utf8Value nodeOrgFilePath(args[0]->ToDetailString());
baton->orgFilePath = string(*nodeOrgFilePath);
baton->uframeDirectory = string("");
baton->torrentDirectory = string("");
baton->uframeFilePath = string("");
baton->torrentFilePath = string("");
baton->uframeHash = string("");
baton->pieceSize = 0;
baton->afterCallBack = &afterMp3ToTorrentImpl;
//ARRAY
if ( !args[1]->IsObject() ){
ThrowException(Exception::TypeError(String::New("Second argument must be an object")));
return scope.Close(Undefined());
}
Handle<Object> object = Handle<Object>::Cast(args[1]);
Handle<Value> objUframeDirectory = object->Get(String::New("uframeDirectory"));
if ( !objUframeDirectory->IsUndefined() )
{
String::Utf8Value nodeUframeDirectory(objUframeDirectory->ToDetailString());
baton->uframeDirectory = string(*nodeUframeDirectory);
}
Handle<Value> objTorrentDirectory = object->Get(String::New("torrentDirectory"));
if ( !objTorrentDirectory->IsUndefined() )
{
String::Utf8Value nodeTorrentDirectory(objTorrentDirectory->ToDetailString());
baton->torrentDirectory = string(*nodeTorrentDirectory);
}
Handle<Value> objPieceSize = object->Get(String::New("pieceSize"));
if ( !objTorrentDirectory->IsUndefined() )
{
Local<Integer> nodePieceSize = objPieceSize->ToInteger();
baton->pieceSize = nodePieceSize->Value();
}
//CALLBACK
baton->callback = Persistent<Function>::New(Local<Function>::Cast(args[2]));
//ESPECIFICO *********
pthread_create(&status_change_thread, NULL, mp3ToTorrentImpl, (void *)baton);
return scope.Close(True());
}
示例15: format
Handle<Value> Grid::encodeSync(const Arguments& args) // format, resolution
{
HandleScope scope;
Grid* g = ObjectWrap::Unwrap<Grid>(args.This());
// defaults
std::string format("utf");
unsigned int resolution = 4;
bool add_features = true;
// accept custom format
if (args.Length() >= 1){
if (!args[0]->IsString())
return ThrowException(Exception::TypeError(
String::New("first arg, 'format' must be a string")));
format = TOSTR(args[0]);
}
// options hash
if (args.Length() >= 2) {
if (!args[1]->IsObject())
return ThrowException(Exception::TypeError(
String::New("optional second arg must be an options object")));
Local<Object> options = args[1]->ToObject();
if (options->Has(String::New("resolution")))
{
Local<Value> bind_opt = options->Get(String::New("resolution"));
if (!bind_opt->IsNumber())
return ThrowException(Exception::TypeError(
String::New("'resolution' must be an Integer")));
resolution = bind_opt->IntegerValue();
}
if (options->Has(String::New("features")))
{
Local<Value> bind_opt = options->Get(String::New("features"));
if (!bind_opt->IsBoolean())
return ThrowException(Exception::TypeError(
String::New("'features' must be an Boolean")));
add_features = bind_opt->BooleanValue();
}
}
try {
Local<Array> grid_array = Array::New();
std::vector<mapnik::grid::lookup_type> key_order;
node_mapnik::grid2utf<mapnik::grid>(*g->get(),grid_array,key_order,resolution);
// convert key order to proper javascript array
Local<Array> keys_a = Array::New(key_order.size());
std::vector<std::string>::iterator it;
unsigned int i;
for (it = key_order.begin(), i = 0; it < key_order.end(); ++it, ++i)
{
keys_a->Set(i, String::New((*it).c_str()));
}
// gather feature data
Local<Object> feature_data = Object::New();
if (add_features) {
node_mapnik::write_features<mapnik::grid>(*g->get(),
feature_data,
key_order
);
}
// Create the return hash.
Local<Object> json = Object::New();
json->Set(String::NewSymbol("grid"), grid_array);
json->Set(String::NewSymbol("keys"), keys_a);
json->Set(String::NewSymbol("data"), feature_data);
return json;
}
catch (std::exception & ex)
{
return ThrowException(Exception::Error(
String::New(ex.what())));
}
}