本文整理汇总了C++中Local::Set方法的典型用法代码示例。如果您正苦于以下问题:C++ Local::Set方法的具体用法?C++ Local::Set怎么用?C++ Local::Set使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Local
的用法示例。
在下文中一共展示了Local::Set方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: Init
void HoneydProfileBinding::Init(v8::Handle<Object> target)
{
// Prepare constructor template
Local<FunctionTemplate> tpl = FunctionTemplate::New(New);
tpl->SetClassName(String::NewSymbol("HoneydProfileBinding"));
tpl->InstanceTemplate()->SetInternalFieldCount(1);
// Prototype
Local<Template> proto = tpl->PrototypeTemplate();
proto->Set("SetName", FunctionTemplate::New(InvokeWrappedMethod<bool, HoneydProfileBinding, NodeProfile, std::string, &Nova::NodeProfile::SetName>));
proto->Set("SetTcpAction", FunctionTemplate::New(InvokeWrappedMethod<bool, HoneydProfileBinding, NodeProfile, std::string, &Nova::NodeProfile::SetTcpAction>));
proto->Set("SetUdpAction", FunctionTemplate::New(InvokeWrappedMethod<bool, HoneydProfileBinding, NodeProfile, std::string, &Nova::NodeProfile::SetUdpAction>));
proto->Set("SetIcmpAction", FunctionTemplate::New(InvokeWrappedMethod<bool, HoneydProfileBinding, NodeProfile, std::string, &Nova::NodeProfile::SetIcmpAction>));
proto->Set("SetPersonality", FunctionTemplate::New(InvokeWrappedMethod<bool, HoneydProfileBinding, NodeProfile, std::string, &Nova::NodeProfile::SetPersonality>));
proto->Set("SetEthernet", FunctionTemplate::New(InvokeWrappedMethod<bool, HoneydProfileBinding, NodeProfile, std::string, &Nova::NodeProfile::SetEthernet>));
proto->Set("SetUptimeMin", FunctionTemplate::New(InvokeWrappedMethod<bool, HoneydProfileBinding, NodeProfile, std::string, &Nova::NodeProfile::SetUptimeMin>));
proto->Set("SetUptimeMax", FunctionTemplate::New(InvokeWrappedMethod<bool, HoneydProfileBinding, NodeProfile, std::string, &Nova::NodeProfile::SetUptimeMax>));
proto->Set("SetDropRate", FunctionTemplate::New(InvokeWrappedMethod<bool, HoneydProfileBinding, NodeProfile, std::string, &Nova::NodeProfile::SetDropRate>));
proto->Set("SetParentProfile", FunctionTemplate::New(InvokeWrappedMethod<bool, HoneydProfileBinding, NodeProfile, std::string, &Nova::NodeProfile::SetParentProfile>));
proto->Set(String::NewSymbol("SetVendors"),FunctionTemplate::New(SetVendors)->GetFunction());
proto->Set("setTcpActionInherited", FunctionTemplate::New(InvokeWrappedMethod<bool, HoneydProfileBinding, NodeProfile, bool, &Nova::NodeProfile::setTcpActionInherited>));
proto->Set("setUdpActionInherited", FunctionTemplate::New(InvokeWrappedMethod<bool, HoneydProfileBinding, NodeProfile, bool, &Nova::NodeProfile::setUdpActionInherited>));
proto->Set("setIcmpActionInherited", FunctionTemplate::New(InvokeWrappedMethod<bool, HoneydProfileBinding, NodeProfile, bool, &Nova::NodeProfile::setIcmpActionInherited>));
proto->Set("setPersonalityInherited",FunctionTemplate::New(InvokeWrappedMethod<bool, HoneydProfileBinding, NodeProfile, bool, &Nova::NodeProfile::setPersonalityInherited>));
proto->Set("setEthernetInherited", FunctionTemplate::New(InvokeWrappedMethod<bool, HoneydProfileBinding, NodeProfile, bool, &Nova::NodeProfile::setEthernetInherited>));
proto->Set("setUptimeInherited", FunctionTemplate::New(InvokeWrappedMethod<bool, HoneydProfileBinding, NodeProfile, bool, &Nova::NodeProfile::setUptimeInherited>));
proto->Set("setDropRateInherited", FunctionTemplate::New(InvokeWrappedMethod<bool, HoneydProfileBinding, NodeProfile, bool, &Nova::NodeProfile::setDropRateInherited>));
proto->Set(String::NewSymbol("Save"),FunctionTemplate::New(Save)->GetFunction());
proto->Set(String::NewSymbol("AddPort"),FunctionTemplate::New(AddPort)->GetFunction());
Persistent<Function> constructor = Persistent<Function>::New(tpl->GetFunction());
target->Set(String::NewSymbol("HoneydProfileBinding"), constructor);
}
示例2: EIO_AfterQuery
int Database::EIO_AfterQuery(eio_req *req) {
//printf("Database::EIO_AfterQuery\n");
ev_unref(EV_DEFAULT_UC);
struct query_request *prep_req = (struct query_request *)(req->data);
HandleScope scope;
Database *self = prep_req->dbo->self(); //an easy reference to the Database object
Local<Object> objError = Object::New(); //our error object which we will use if we discover errors while processing the result set
short colCount = 0; //used to keep track of the number of columns received in a result set
short emitCount = 0; //used to keep track of the number of event emittions that have occurred
short errorCount = 0; //used to keep track of the number of errors that have been found
SQLSMALLINT buflen; //used as a place holder for the length of column names
SQLRETURN ret; //used to capture the return value from various SQL function calls
char *buf = (char *) malloc(MAX_VALUE_SIZE); //allocate a buffer for incoming column values
//check to make sure malloc succeeded
if (buf == NULL) {
//malloc failed, set an error message
objError->Set(String::New("error"), String::New("[node-odbc] Failed Malloc"));
objError->Set(String::New("message"), String::New("An attempt to allocate memory failed. This allocation was for a value buffer of incoming recordset values."));
//emit an error event immidiately.
Local<Value> args[3];
args[0] = objError;
args[1] = Local<Value>::New(Null());
args[2] = Local<Boolean>::New(False());
//emit an error event
self->Emit(String::New("error"), 3, args);
//emit a result event
self->Emit(String::New("result"), 3, args);
}
else {
//malloc succeeded so let's continue -- I'm not too fond of having all this code in the else statement, but I don't know what else to do...
memset(buf,0,MAX_VALUE_SIZE); //set all of the bytes of the buffer to 0; I tried doing this inside the loop, but it increased processing time dramatically
struct tm timeInfo = { 0 }; //used for processing date/time datatypes
//First thing, let's check if the execution of the query returned any errors (in EIO_Query)
if(req->result == SQL_ERROR)
{
errorCount++;
char errorMessage[512];
char errorSQLState[128];
SQLError(self->m_hEnv, self->m_hDBC, self->m_hStmt,(SQLCHAR *)errorSQLState,NULL,(SQLCHAR *)errorMessage, sizeof(errorMessage), NULL);
objError->Set(String::New("state"), String::New(errorSQLState));
objError->Set(String::New("error"), String::New("[node-odbc] SQL_ERROR"));
objError->Set(String::New("message"), String::New(errorMessage));
//only set the query value of the object if we actually have a query
if (prep_req->sql != NULL) {
objError->Set(String::New("query"), String::New(prep_req->sql));
}
//emit an error event immidiately.
Local<Value> args[1];
args[0] = objError;
self->Emit(String::New("error"), 1, args);
}
//loop through all result sets
do {
colCount = 0; //always reset colCount for the current result set to 0;
SQLNumResultCols(self->m_hStmt, &colCount);
Column *columns = new Column[colCount];
Local<Array> rows = Array::New();
if (colCount > 0) {
// retrieve and store column attributes to build the row object
for(int i = 0; i < colCount; i++)
{
columns[i].name = new unsigned char[MAX_FIELD_SIZE];
//zero out the space where the column name will be stored
memset(columns[i].name, 0, MAX_FIELD_SIZE);
//get the column name
ret = SQLColAttribute(self->m_hStmt, (SQLUSMALLINT)i+1, SQL_DESC_LABEL, columns[i].name, (SQLSMALLINT)MAX_FIELD_SIZE, (SQLSMALLINT *)&buflen, NULL);
//store the len attribute
columns[i].len = buflen;
//get the column type and store it directly in column[i].type
ret = SQLColAttribute( self->m_hStmt, (SQLUSMALLINT)i+1, SQL_COLUMN_TYPE, NULL, 0, NULL, &columns[i].type );
}
int count = 0;
// i dont think odbc will tell how many rows are returned, loop until out...
while(true)
{
//.........这里部分代码省略.........
示例3: sizeof
Local<Function> MetadataNode::SetMembersFromStaticMetadata(Isolate *isolate, Local<FunctionTemplate>& ctorFuncTemplate, Local<ObjectTemplate>& prototypeTemplate, vector<MethodCallbackData*>& instanceMethodsCallbackData, const vector<MethodCallbackData*>& baseInstanceMethodsCallbackData, MetadataTreeNode *treeNode)
{
SET_PROFILER_FRAME();
Local<Function> ctorFunction;
uint8_t *curPtr = s_metadataReader.GetValueData() + treeNode->offsetValue + 1;
auto nodeType = s_metadataReader.GetNodeType(treeNode);
auto curType = s_metadataReader.ReadTypeName(treeNode);
curPtr += sizeof(uint16_t /* baseClassId */);
if (s_metadataReader.IsNodeTypeInterface(nodeType))
{
curPtr += sizeof(uint8_t) + sizeof(uint32_t);
}
//get candidates from instance methods metadata
auto instanceMethodCout = *reinterpret_cast<uint16_t*>(curPtr);
curPtr += sizeof(uint16_t);
string lastMethodName;
MethodCallbackData *callbackData = nullptr;
for (auto i = 0; i < instanceMethodCout; i++)
{
auto entry = s_metadataReader.ReadInstanceMethodEntry(&curPtr);
if (entry.name != lastMethodName)
{
callbackData = new MethodCallbackData(this);
instanceMethodsCallbackData.push_back(callbackData);
auto itBegin = baseInstanceMethodsCallbackData.begin();
auto itEnd = baseInstanceMethodsCallbackData.end();
auto itFound = find_if(itBegin, itEnd, [&entry] (MethodCallbackData *x)
{ return x->candidates.front().name == entry.name;});
if (itFound != itEnd)
{
callbackData->parent = *itFound;
}
auto funcData = External::New(isolate, callbackData);
auto funcTemplate = FunctionTemplate::New(isolate, MethodCallback, funcData);
auto funcName = ConvertToV8String(entry.name);
prototypeTemplate->Set(funcName, funcTemplate->GetFunction());
lastMethodName = entry.name;
}
callbackData->candidates.push_back(entry);
}
//get candidates from instance fields metadata
auto instanceFieldCout = *reinterpret_cast<uint16_t*>(curPtr);
curPtr += sizeof(uint16_t);
for (auto i = 0; i < instanceFieldCout; i++)
{
auto entry = s_metadataReader.ReadInstanceFieldEntry(&curPtr);
auto fieldName = ConvertToV8String(entry.name);
auto fieldInfo = new FieldCallbackData(entry);
fieldInfo->declaringType = curType;
auto fieldData = External::New(isolate, fieldInfo);
prototypeTemplate->SetAccessor(fieldName, FieldAccessorGetterCallback, FieldAccessorSetterCallback, fieldData, AccessControl::DEFAULT, PropertyAttribute::DontDelete);
}
ctorFunction = ctorFuncTemplate->GetFunction();
//get candidates from static methods metadata
callbackData = nullptr;
lastMethodName.clear();
auto staticMethodCout = *reinterpret_cast<uint16_t*>(curPtr);
curPtr += sizeof(uint16_t);
for (auto i = 0; i < staticMethodCout; i++)
{
auto entry = s_metadataReader.ReadStaticMethodEntry(&curPtr);
if (entry.name != lastMethodName)
{
callbackData = new MethodCallbackData(this);
auto funcData = External::New(isolate, callbackData);
auto funcTemplate = FunctionTemplate::New(isolate, MethodCallback, funcData);
auto funcName = ConvertToV8String(entry.name);
ctorFunction->Set(funcName, funcTemplate->GetFunction());
lastMethodName = entry.name;
}
callbackData->candidates.push_back(entry);
}
auto extendFuncName = V8StringConstants::GetExtend();
auto extendFuncTemplate = FunctionTemplate::New(isolate, ExtendCallMethodCallback, External::New(isolate, this));
ctorFunction->Set(extendFuncName, extendFuncTemplate->GetFunction());
//get candidates from static fields metadata
auto staticFieldCout = *reinterpret_cast<uint16_t*>(curPtr);
curPtr += sizeof(uint16_t);
for (auto i = 0; i < staticFieldCout; i++)
{
auto entry = s_metadataReader.ReadStaticFieldEntry(&curPtr);
auto fieldName = ConvertToV8String(entry.name);
auto fieldData = External::New(isolate, new FieldCallbackData(entry));
ctorFunction->SetAccessor(fieldName, FieldAccessorGetterCallback, FieldAccessorSetterCallback, fieldData, AccessControl::DEFAULT, PropertyAttribute::DontDelete);
//.........这里部分代码省略.........
示例4: if
/*
* Prototype:
* TBW
*
* Docs:
* TBW
*
* Example:
* TBW
*/
static void
gum_script_thread_on_backtrace (const FunctionCallbackInfo<Value> & info)
{
GumScriptThread * self = static_cast<GumScriptThread *> (
info.Data ().As<External> ()->Value ());
Isolate * isolate = info.GetIsolate ();
int num_args = info.Length ();
GumCpuContext * cpu_context = NULL;
if (num_args >= 1)
{
Local<Value> value = info[0];
if (!value->IsNull ())
{
if (!_gum_script_cpu_context_get (value, &cpu_context, self->core))
return;
}
}
bool accurate = true;
if (num_args >= 2)
{
Local<Value> selector = info[1];
if (!selector->IsNull ())
{
if ((*self->fuzzy_enum_value) == selector)
{
accurate = false;
}
else if ((*self->accurate_enum_value) != selector)
{
isolate->ThrowException (Exception::TypeError (String::NewFromUtf8 (
isolate, "Thread.backtrace: invalid backtracer enum value")));
return;
}
}
}
GumBacktracer * backtracer;
if (accurate)
{
if (self->accurate_backtracer == NULL)
self->accurate_backtracer = gum_backtracer_make_accurate ();
backtracer = self->accurate_backtracer;
}
else
{
if (self->fuzzy_backtracer == NULL)
self->fuzzy_backtracer = gum_backtracer_make_fuzzy ();
backtracer = self->fuzzy_backtracer;
}
if (backtracer == NULL)
{
isolate->ThrowException (Exception::TypeError (String::NewFromUtf8 (
isolate, accurate
? "Thread.backtrace: backtracer not yet available for this "
"platform; please try Thread.backtrace(context, Backtracer.FUZZY)"
: "Thread.backtrace: backtracer not yet available for this "
"platform; please try Thread.backtrace(context, Backtracer.ACCURATE)"
)));
return;
}
GumReturnAddressArray ret_addrs;
gum_backtracer_generate (backtracer, cpu_context, &ret_addrs);
Local<Array> result = Array::New (isolate, ret_addrs.len);
for (guint i = 0; i != ret_addrs.len; i++)
result->Set (i, _gum_script_pointer_new (ret_addrs.items[i], self->core));
info.GetReturnValue ().Set (result);
}
示例5: getNamedCons
Local<v8::Object> mongoToV8( const BSONObj& m , bool array, bool readOnly ){
// handle DBRef. needs to come first. isn't it? (metagoto)
static string ref = "$ref";
if ( ref == m.firstElement().fieldName() ) {
const BSONElement& id = m["$id"];
if (!id.eoo()) { // there's no check on $id exitence in sm implementation. risky ?
v8::Function* dbRef = getNamedCons( "DBRef" );
v8::Handle<v8::Value> argv[2];
argv[0] = mongoToV8Element(m.firstElement());
argv[1] = mongoToV8Element(m["$id"]);
return dbRef->NewInstance(2, argv);
}
}
Local< v8::ObjectTemplate > readOnlyObjects;
// Hoping template construction is fast...
Local< v8::ObjectTemplate > internalFieldObjects = v8::ObjectTemplate::New();
internalFieldObjects->SetInternalFieldCount( 1 );
Local<v8::Object> o;
if ( array ) {
// NOTE Looks like it's impossible to add interceptors to non array objects in v8.
o = v8::Array::New();
} else if ( !readOnly ) {
o = v8::Object::New();
} else {
// NOTE Our readOnly implemention relies on undocumented ObjectTemplate
// functionality that may be fragile, but it still seems like the best option
// for now -- fwiw, the v8 docs are pretty sparse. I've determined experimentally
// that when property handlers are set for an object template, they will attach
// to objects previously created by that template. To get this to work, though,
// it is necessary to initialize the template's property handlers before
// creating objects from the template (as I have in the following few lines
// of code).
// NOTE In my first attempt, I configured the permanent property handlers before
// constructiong the object and replaced the Set() calls below with ForceSet().
// However, it turns out that ForceSet() only bypasses handlers for named
// properties and not for indexed properties.
readOnlyObjects = v8::ObjectTemplate::New();
// NOTE This internal field will store type info for special db types. For
// regular objects the field is unnecessary - for simplicity I'm creating just
// one readOnlyObjects template for objects where the field is & isn't necessary,
// assuming that the overhead of an internal field is slight.
readOnlyObjects->SetInternalFieldCount( 1 );
readOnlyObjects->SetNamedPropertyHandler( 0 );
readOnlyObjects->SetIndexedPropertyHandler( 0 );
o = readOnlyObjects->NewInstance();
}
mongo::BSONObj sub;
for ( BSONObjIterator i(m); i.more(); ) {
const BSONElement& f = i.next();
Local<Value> v;
switch ( f.type() ){
case mongo::Code:
o->Set( v8::String::New( f.fieldName() ), newFunction( f.valuestr() ) );
break;
case CodeWScope:
if ( f.codeWScopeObject().isEmpty() )
log() << "warning: CodeWScope doesn't transfer to db.eval" << endl;
o->Set( v8::String::New( f.fieldName() ), newFunction( f.codeWScopeCode() ) );
break;
case mongo::String:
o->Set( v8::String::New( f.fieldName() ) , v8::String::New( f.valuestr() ) );
break;
case mongo::jstOID: {
v8::Function * idCons = getObjectIdCons();
v8::Handle<v8::Value> argv[1];
argv[0] = v8::String::New( f.__oid().str().c_str() );
o->Set( v8::String::New( f.fieldName() ) ,
idCons->NewInstance( 1 , argv ) );
break;
}
case mongo::NumberDouble:
case mongo::NumberInt:
o->Set( v8::String::New( f.fieldName() ) , v8::Number::New( f.number() ) );
break;
case mongo::Array:
case mongo::Object:
sub = f.embeddedObject();
o->Set( v8::String::New( f.fieldName() ) , mongoToV8( sub , f.type() == mongo::Array, readOnly ) );
break;
case mongo::Date:
o->Set( v8::String::New( f.fieldName() ) , v8::Date::New( f.date() ) );
break;
case mongo::Bool:
o->Set( v8::String::New( f.fieldName() ) , v8::Boolean::New( f.boolean() ) );
break;
//.........这里部分代码省略.........
示例6: UV_AfterFetchAll
void ODBCResult::UV_AfterFetchAll(uv_work_t* work_req, int status) {
DEBUG_PRINTF("ODBCResult::UV_AfterFetchAll\n");
NanScope();
fetch_work_data* data = (fetch_work_data *)(work_req->data);
ODBCResult* self = data->objResult->self();
bool doMoreWork = true;
if (self->colCount == 0) {
self->columns = ODBC::GetColumns(self->m_hSTMT, &self->colCount);
}
//check to see if the result set has columns
if (self->colCount == 0) {
//this most likely means that the query was something like
//'insert into ....'
doMoreWork = false;
}
//check to see if there was an error
else if (data->result == SQL_ERROR) {
data->errorCount++;
NanAssignPersistent(data->objError, ODBC::GetSQLError(
SQL_HANDLE_STMT,
self->m_hSTMT,
(char *) "[node-odbc] Error in ODBCResult::UV_AfterFetchAll"
));
doMoreWork = false;
}
//check to see if we are at the end of the recordset
else if (data->result == SQL_NO_DATA) {
doMoreWork = false;
}
else {
//TODO: !important: persistent forces us to set this to a local handle, but do we need to recopy it back to persistent handle?
Local<Array> rows = NanNew(data->rows);
if (data->fetchMode == FETCH_ARRAY) {
rows->Set(
NanNew(data->count),
ODBC::GetRecordArray(
self->m_hSTMT,
self->columns,
&self->colCount,
self->buffer,
self->bufferLength)
);
}
else {
rows->Set(
NanNew(data->count),
ODBC::GetRecordTuple(
self->m_hSTMT,
self->columns,
&self->colCount,
self->buffer,
self->bufferLength)
);
}
data->count++;
}
if (doMoreWork) {
//Go back to the thread pool and fetch more data!
uv_queue_work(
uv_default_loop(),
work_req,
UV_FetchAll,
(uv_after_work_cb)UV_AfterFetchAll);
}
else {
ODBC::FreeColumns(self->columns, &self->colCount);
Handle<Value> args[2];
if (data->errorCount > 0) {
args[0] = NanNew(data->objError);
}
else {
args[0] = NanNull();
}
args[1] = NanNew(data->rows);
TryCatch try_catch;
data->cb->Call(2, args);
delete data->cb;
NanDisposePersistent(data->rows);
NanDisposePersistent(data->objError);
if (try_catch.HasCaught()) {
FatalException(try_catch);
}
//TODO: Do we need to free self->rows somehow?
free(data);
free(work_req);
//.........这里部分代码省略.........
示例7: QueryAsync
void MySQL::QueryAsync(int id, string query, Persistent<Function, CopyablePersistentTraits<Function>> callback){
// We need to do this or for some reason it loses its persistence and goes out of scope :(
Persistent<Function, CopyablePersistentTraits<Function>> cb;
cb.Reset(isolate, callback);
thread( [this, id, cb, query](){
mysql_thread_init();
std::lock_guard<std::mutex> lock{ connections[id]->lock };
MYSQL* msql = connections[id]->mysql;
if (!isConnected(msql)){
sjs::logger::error("MYSQL Error: Not connected");
} else {
mysql_query(msql, query.c_str());
unsigned int err_no = mysql_errno(msql);
if (err_no){
sjs::logger::error("MYSQL Query Error: %s", mysql_error(msql));
V8PCONTEXT(isolate, context);
TryCatch try_catch;
Local<String> err = String::NewFromUtf8(isolate, mysql_error(msql));
Local<Value> argv[1] = { err };
Local<Function> func = Local<Function>::New(isolate, cb);
func->Call(func, 1, argv);
if (try_catch.HasCaught()){
Utils::PrintException(&try_catch);
}
mysql_thread_end();
return;
}
MYSQL_RES *result = mysql_store_result(msql);
if (result == NULL){
// No error and result was null meaning it wasn't a SELECT type statement
my_ulonglong affected = mysql_affected_rows(msql);
my_ulonglong insert_id = mysql_insert_id(msql);
V8PCONTEXT(isolate, context);
TryCatch try_catch;
JS_Object jsresult(isolate);
jsresult.Set("insertId", insert_id);
jsresult.Set("affectedRows", affected);
Local<Value> empty = Undefined(isolate);
Local<Value> argv[2] = { empty, jsresult.get() };
Local<Function> func = Local<Function>::New(isolate, cb);
func->Call(func, 2, argv);
if (try_catch.HasCaught()){
Utils::PrintException(&try_catch);
}
}
else {
int num_fields = mysql_num_fields(result);
MYSQL_ROW row;
MYSQL_FIELD *field;
vector<string> fields;
V8PCONTEXT(isolate, context);
TryCatch try_catch;
Local<Array> jsrows = Array::New(isolate, 0);
Local<Array> jsfields = Array::New(isolate, num_fields);
for (int j = 0; j < num_fields; j++){
field = mysql_fetch_field_direct(result, j);
fields.push_back(field->name);
jsfields->Set(j, String::NewFromUtf8(isolate, field->name));
}
int row_count = 0;
while ((row = mysql_fetch_row(result))){
JS_Object jsrow(isolate);
for (int i = 0; i < num_fields; i++){
if (row[i] == NULL) jsrow.SetNull(fields[i]);
else jsrow.Set(fields[i], string(row[i]));
}
jsrows->Set(row_count++, jsrow.get());
}
Local<Value> empty = Undefined(isolate);
Local<Value> argv[3] = { empty, jsrows, jsfields };
Local<Function> func = Local<Function>::New(isolate, cb);
//.........这里部分代码省略.........
示例8: Init
void SimpleProfiler::Init(Isolate *isolate, Local<ObjectTemplate>& globalTemplate)
{
s_frames.reserve(10000);
auto funcName = String::NewFromUtf8(isolate, "__printProfilerData");
globalTemplate->Set(funcName, FunctionTemplate::New(isolate, PrintProfilerDataCallback));
}
示例9: SQLGetDiagField
Local<Object> ODBC::GetSQLError (SQLSMALLINT handleType, SQLHANDLE handle, char* message) {
Nan::EscapableHandleScope scope;
DEBUG_PRINTF("ODBC::GetSQLError : handleType=%i, handle=%p\n", handleType, handle);
Local<Object> objError = Nan::New<Object>();
SQLINTEGER i = 0;
SQLINTEGER native;
SQLSMALLINT len;
SQLINTEGER statusRecCount;
SQLRETURN ret;
char errorSQLState[14];
char errorMessage[ERROR_MESSAGE_BUFFER_BYTES];
ret = SQLGetDiagField(
handleType,
handle,
0,
SQL_DIAG_NUMBER,
&statusRecCount,
SQL_IS_INTEGER,
&len);
// Windows seems to define SQLINTEGER as long int, unixodbc as just int... %i should cover both
DEBUG_PRINTF("ODBC::GetSQLError : called SQLGetDiagField; ret=%i, statusRecCount=%i\n", ret, statusRecCount);
Local<Array> errors = Nan::New<Array>();
objError->Set(Nan::New("errors").ToLocalChecked(), errors);
for (i = 0; i < statusRecCount; i++) {
DEBUG_PRINTF("ODBC::GetSQLError : calling SQLGetDiagRec; i=%i, statusRecCount=%i\n", i, statusRecCount);
ret = SQLGetDiagRec(
handleType,
handle,
(SQLSMALLINT)(i + 1),
(SQLTCHAR *) errorSQLState,
&native,
(SQLTCHAR *) errorMessage,
ERROR_MESSAGE_BUFFER_CHARS,
&len);
DEBUG_PRINTF("ODBC::GetSQLError : after SQLGetDiagRec; i=%i\n", i);
if (SQL_SUCCEEDED(ret)) {
DEBUG_PRINTF("ODBC::GetSQLError : errorMessage=%s, errorSQLState=%s\n", errorMessage, errorSQLState);
if (i == 0) {
// First error is assumed the primary error
objError->Set(Nan::New("error").ToLocalChecked(), Nan::New(message).ToLocalChecked());
#ifdef UNICODE
objError->SetPrototype(Exception::Error(Nan::New((uint16_t *)errorMessage).ToLocalChecked()));
objError->Set(Nan::New("message").ToLocalChecked(), Nan::New((uint16_t *)errorMessage).ToLocalChecked());
objError->Set(Nan::New("state").ToLocalChecked(), Nan::New((uint16_t *)errorSQLState).ToLocalChecked());
#else
objError->SetPrototype(Exception::Error(Nan::New(errorMessage).ToLocalChecked()));
objError->Set(Nan::New("message").ToLocalChecked(), Nan::New(errorMessage).ToLocalChecked());
objError->Set(Nan::New("state").ToLocalChecked(), Nan::New(errorSQLState).ToLocalChecked());
#endif
}
Local<Object> subError = Nan::New<Object>();
#ifdef UNICODE
subError->Set(Nan::New("message").ToLocalChecked(), Nan::New((uint16_t *)errorMessage).ToLocalChecked());
subError->Set(Nan::New("state").ToLocalChecked(), Nan::New((uint16_t *)errorSQLState).ToLocalChecked());
#else
subError->Set(Nan::New("message").ToLocalChecked(), Nan::New(errorMessage).ToLocalChecked());
subError->Set(Nan::New("state").ToLocalChecked(), Nan::New(errorSQLState).ToLocalChecked());
#endif
errors->Set(Nan::New(i), subError);
} else if (ret == SQL_NO_DATA) {
break;
}
}
if (statusRecCount == 0) {
//Create a default error object if there were no diag records
objError->Set(Nan::New("error").ToLocalChecked(), Nan::New(message).ToLocalChecked());
objError->SetPrototype(Exception::Error(Nan::New(message).ToLocalChecked()));
objError->Set(Nan::New("message").ToLocalChecked(), Nan::New(
(const char *) "[node-odbc] An error occurred but no diagnostic information was available.").ToLocalChecked());
}
return scope.Escape(objError);
}
示例10: JS_CallNative
void Server::JS_CallNative(const FunctionCallbackInfo<Value> & args){
typedef int(*amx_Function_t)(AMX * amx, cell * params);
TryCatch try_catch;
if (args.Length() < 1){
sjs::logger::error("Function CallNative requires at least 1 argument CallNative(nativeName, params, args);");
args.GetReturnValue().SetNull();
return;
}
std::string func_name = JS2STRING(args[0]);
int func_idx;
AMX_HEADER *amx_hdr = (AMX_HEADER *)SAMPJS::amx->base;
auto iter = _native_func_cache.find(func_name);
if (iter != _native_func_cache.end()) func_idx = iter->second;
else {
if (amx_FindNative(SAMPJS::amx, func_name.c_str(), &func_idx)){
sjs::logger::error("Cannot find native function %s", func_name.c_str());
return;
}
_native_func_cache[func_name] = func_idx;
}
unsigned int amx_addr = (unsigned int)((AMX_FUNCSTUB *)((char *)amx_hdr + amx_hdr->natives + amx_hdr->defsize * func_idx))->address;
if (args.Length() > 1){
if (!args[1]->IsString()){
sjs::logger::error("CallNative %s, 2nd argument must be a string", func_name.c_str());
return;
}
std::string param = JS2STRING(args[1]);
size_t S_oc = std::count(param.begin(), param.end(), 'S');
size_t I_oc = std::count(param.begin(), param.end(), 'I');
size_t F_oc = std::count(param.begin(), param.end(), 'F');
bool multi = false;
if ((S_oc + I_oc + F_oc) > 1) multi = true;
if (!args[args.Length() - 1]->IsArray() && multi){
sjs::logger::error("CallNative %s, you must supply an array of strings for functions with multiple references", func_name.c_str());
return;
}
unsigned int count = (param.length()), variables = 0;
cell *physAddr[6];
cell *params = new cell[count + 1];
params[0] = count * sizeof(cell);
unsigned int strVars = 0;
unsigned int k = 2, j = 1;
for (unsigned int i = 0; i < param.length(); i++){
switch (param[i]){
case 'd':
case 'i':
{
int val = 0;
if (!args[k]->IsUndefined()) val = args[k]->Int32Value();
params[j++] = val;
k++;
break;
}
case 'f':
{
float val = 0.0;
if (!args[k]->IsUndefined()) val = (float)args[k]->NumberValue();
params[j++] = amx_ftoc(val);
k++;
break;
}
case 's':
{
std::string str = "";
if (!args[k]->IsUndefined()) str = JS2STRING(args[k]);
const char* val = str.c_str();
amx_Allot(SAMPJS::amx, strlen(val) + 1, ¶ms[j++], &physAddr[variables++]);
amx_SetString(physAddr[variables - 1], val, 0, 0, strlen(val) + 1);
k++;
break;
}
case 'F':
case 'I':
{
amx_Allot(SAMPJS::amx, 1, ¶ms[j++], &physAddr[variables++]);
break;
}
case 'S':
{
int strlen = args[k++]->Int32Value();
amx_Allot(SAMPJS::amx, strlen, ¶ms[j++], &physAddr[variables++]);
params[j++] = strlen;
i++;
break;
//.........这里部分代码省略.........
示例11: Execute
// Implementation of the schema handler for appjs:// requests.
void AppjsSchemeHandler::Execute(CefThreadId threadId) {
REQUIRE_UI_THREAD();
HandleScope scope;
Local<Object> global = Context::GetCurrent()->Global();
Local<Object> emitter = global->Get(String::NewSymbol("process"))->ToObject();
const int argc = 3;
Handle<Value> self = WrapObject(this);
Local<Function> cb = FunctionTemplate::New(NodeCallback,self)->GetFunction();
Local<Object> req = Object::New();
Local<String> post = String::New("");
Local<Object> headers = Object::New();
Local<String> files = String::New("");
CefRequest::HeaderMap headerMap;
request_->GetHeaderMap(headerMap);
if (headerMap.size() > 0) {
CefRequest::HeaderMap::const_iterator it = headerMap.begin();
for ( ; it != headerMap.end(); ++it) {
headers->Set(String::New((uint16_t*)(*it).first.c_str()),String::New((uint16_t*)(*it).second.c_str()));
}
}
CefRefPtr<CefPostData> postData = request_->GetPostData();
if(postData.get()){
CefPostData::ElementVector elements;
postData->GetElements(elements);
if (elements.size() > 0) {
CefRefPtr<CefPostDataElement> element;
CefPostData::ElementVector::const_iterator it = elements.begin();
for ( ; it != elements.end(); ++it) {
element = (*it);
if (element->GetType() == PDE_TYPE_BYTES && element->GetBytesCount()) {
// retrieve the data.
size_t size = element->GetBytesCount();
char* bytes = new char[size];
element->GetBytes(size, bytes);
post = String::New(bytes,size);
delete [] bytes;
} else if (element->GetType() == PDE_TYPE_FILE) {
//TODO Needs testing
files = String::New((uint16_t*)element->GetFile().c_str());
}
}
}
}
Handle<Value> method = String::New((uint16_t*)request_->GetMethod().c_str());
Handle<Value> url = String::New((uint16_t*)request_->GetURL().c_str());
req->Set(String::NewSymbol("method"),method);
req->Set(String::NewSymbol("url"),url);
req->Set(String::NewSymbol("post"),post);
req->Set(String::NewSymbol("headers"),headers);
req->Set(String::NewSymbol("files"),files);
Handle<Value> argv[argc] = {String::New("appjs-request"),req,cb};
node::MakeCallback(emitter,"emit",argc,argv);
}
示例12: GLESglGetParameterCallback
//.........这里部分代码省略.........
case GL_STENCIL_PASS_DEPTH_PASS:
case GL_STENCIL_REF:
case GL_STENCIL_VALUE_MASK:
case GL_STENCIL_WRITEMASK:
// case GL_TEXTURE_1D_BINDING:
// case GL_TEXTURE_2D_BINDING:
case GL_TEXTURE_COORD_ARRAY_SIZE:
case GL_TEXTURE_COORD_ARRAY_STRIDE:
case GL_TEXTURE_COORD_ARRAY_TYPE:
case GL_TEXTURE_STACK_DEPTH:
case GL_UNPACK_ALIGNMENT:
case GL_UNPACK_ROW_LENGTH:
case GL_UNPACK_SKIP_PIXELS:
case GL_UNPACK_SKIP_ROWS:
case GL_VERTEX_ARRAY_SIZE:
case GL_VERTEX_ARRAY_STRIDE:
case GL_VERTEX_ARRAY_TYPE:
{
int ans = 0;
glGetIntegerv((GLenum)pname, (GLint*)&ans);
return handle_scope.Close(Integer::New(ans));
}
//2 values int
case GL_LINE_WIDTH_RANGE:
case GL_MAP2_GRID_SEGMENTS:
case GL_MAX_VIEWPORT_DIMS:
case GL_POLYGON_MODE:
{
int* ans = new int[2];
glGetIntegerv((GLenum)pname, ans);
Local<Array> res = Array::New(2);
for (int i = 0; i < 2; ++i) {
res->Set(Integer::New(i), Integer::New(ans[i]));
}
delete[] ans;
return handle_scope.Close(res);
}
//4 values int
case GL_SCISSOR_BOX:
case GL_VIEWPORT:
{
int* ans = new int[4];
glGetIntegerv((GLenum)pname, ans);
Local<Array> res = Array::New(4);
for (int i = 0; i < 4; ++i) {
res->Set(Integer::New(i), Integer::New(ans[i]));
}
delete[] ans;
return handle_scope.Close(res);
}
//1 value boolean
case GL_ALPHA_TEST:
case GL_AUTO_NORMAL:
case GL_BLEND:
case GL_DEPTH_TEST:
// case GL_CLIP_PLANEi:
case GL_COLOR_ARRAY:
case GL_COLOR_LOGIC_OP:
case GL_COLOR_MATERIAL:
示例13: scope
JNIEXPORT jboolean JNICALL
Java_org_appcelerator_kroll_runtime_v8_V8Object_nativeFireEvent
(JNIEnv *env, jobject jEmitter, jlong ptr, jobject jsource, jlong sourcePtr, jstring event, jobject data, jboolean bubble, jboolean reportSuccess, jint code, jstring errorMessage)
{
HandleScope scope(V8Runtime::v8_isolate);
JNIScope jniScope(env);
Local<Value> jsEvent = TypeConverter::javaStringToJsString(V8Runtime::v8_isolate, env, event);
#ifdef TI_DEBUG
titanium::Utf8Value eventName(jsEvent);
LOGV(TAG, "firing event \"%s\"", *eventName);
#endif
Local<Object> emitter;
if (ptr != 0) {
titanium::Proxy* proxy = (titanium::Proxy*) ptr;
emitter = proxy->handle(V8Runtime::v8_isolate);
} else {
emitter = TypeConverter::javaObjectToJsValue(V8Runtime::v8_isolate, env, jEmitter).As<Object>();
}
Local<Value> fireEventValue = emitter->Get(EventEmitter::emitSymbol.Get(V8Runtime::v8_isolate));
if (!fireEventValue->IsFunction()) {
return JNI_FALSE;
}
Local<Object> source;
if ((jsource == NULL) || (jsource == jEmitter)) {
source = emitter;
} else if (sourcePtr != 0) {
titanium::Proxy* proxy = (titanium::Proxy*) sourcePtr;
source = proxy->handle(V8Runtime::v8_isolate);
} else {
source = TypeConverter::javaObjectToJsValue(V8Runtime::v8_isolate, env, jsource).As<Object>();
}
Local<Function> fireEvent = fireEventValue.As<Function>();
Local<Object> jsData = TypeConverter::javaHashMapToJsValue(V8Runtime::v8_isolate, env, data);
jsData->Set(NEW_SYMBOL(V8Runtime::v8_isolate, "bubbles"), TypeConverter::javaBooleanToJsBoolean(V8Runtime::v8_isolate, bubble));
jsData->Set(NEW_SYMBOL(V8Runtime::v8_isolate, "source"), source);
if (reportSuccess || code != 0) {
jsData->Set(NEW_SYMBOL(V8Runtime::v8_isolate, "success"), TypeConverter::javaBooleanToJsBoolean(V8Runtime::v8_isolate, code == 0));
jsData->Set(NEW_SYMBOL(V8Runtime::v8_isolate, "code"), TypeConverter::javaIntToJsNumber(V8Runtime::v8_isolate, code));
}
if (errorMessage != NULL) {
jsData->Set(NEW_SYMBOL(V8Runtime::v8_isolate, "error"), TypeConverter::javaStringToJsString(V8Runtime::v8_isolate, env, errorMessage));
}
TryCatch tryCatch(V8Runtime::v8_isolate);
Local<Value> args[] = { jsEvent, jsData };
MaybeLocal<Value> result = fireEvent->Call(V8Runtime::v8_isolate->GetCurrentContext(), emitter, 2, args);
if (tryCatch.HasCaught()) {
V8Util::openJSErrorDialog(V8Runtime::v8_isolate, tryCatch);
V8Util::reportException(V8Runtime::v8_isolate, tryCatch);
} else if (result.IsEmpty()) {
return JNI_FALSE;
} else if (result.ToLocalChecked()->IsTrue()) {
return JNI_TRUE;
}
return JNI_FALSE;
}
示例14: SQLGetDiagField
Local<Object> ODBC::GetSQLError (SQLSMALLINT handleType, SQLHANDLE handle, char* message) {
HandleScope scope;
DEBUG_PRINTF("ODBC::GetSQLError : handleType=%i, handle=%p\n", handleType, handle);
Local<Object> objError = Object::New();
Local<String> str = String::New("");
SQLINTEGER i = 0;
SQLINTEGER native;
SQLSMALLINT len;
SQLINTEGER statusRecCount;
SQLRETURN ret;
char errorSQLState[14];
char errorMessage[ERROR_MESSAGE_BUFFER_BYTES];
ret = SQLGetDiagField(
handleType,
handle,
0,
SQL_DIAG_NUMBER,
&statusRecCount,
SQL_IS_INTEGER,
&len);
// Windows seems to define SQLINTEGER as long int, unixodbc as just int... %i should cover both
DEBUG_PRINTF("ODBC::GetSQLError : called SQLGetDiagField; ret=%i, statusRecCount=%i\n", ret, statusRecCount);
for (i = 0; i < statusRecCount; i++){
DEBUG_PRINTF("ODBC::GetSQLError : calling SQLGetDiagRec; i=%i, statusRecCount=%i\n", i, statusRecCount);
ret = SQLGetDiagRec(
handleType,
handle,
i + 1,
(SQLTCHAR *) errorSQLState,
&native,
(SQLTCHAR *) errorMessage,
ERROR_MESSAGE_BUFFER_CHARS,
&len);
DEBUG_PRINTF("ODBC::GetSQLError : after SQLGetDiagRec; i=%i\n", i);
if (SQL_SUCCEEDED(ret)) {
DEBUG_PRINTF("ODBC::GetSQLError : errorMessage=%s, errorSQLState=%s\n", errorMessage, errorSQLState);
objError->Set(String::New("error"), String::New(message));
#ifdef UNICODE
str = String::Concat(str, String::New((uint16_t *) errorMessage));
objError->SetPrototype(Exception::Error(String::New((uint16_t *) errorMessage)));
objError->Set(String::New("message"), str);
objError->Set(String::New("state"), String::New((uint16_t *) errorSQLState));
#else
str = String::Concat(str, String::New(errorMessage));
objError->SetPrototype(Exception::Error(String::New(errorMessage)));
objError->Set(String::New("message"), str);
objError->Set(String::New("state"), String::New(errorSQLState));
#endif
} else if (ret == SQL_NO_DATA) {
break;
}
}
if (statusRecCount == 0) {
//Create a default error object if there were no diag records
objError->Set(String::New("error"), String::New(message));
objError->SetPrototype(Exception::Error(String::New(message)));
objError->Set(String::New("message"), String::New(
(const char *) "[node-odbc] An error occurred but no diagnostic information was available."));
}
return scope.Close(objError);
}
示例15: ThrowException
Handle<Value> ProjTransform::forward(const Arguments& args)
{
HandleScope scope;
ProjTransform* p = ObjectWrap::Unwrap<ProjTransform>(args.This());
if (!args.Length() == 1)
return ThrowException(Exception::Error(
String::New("Must provide an array of either [x,y] or [minx,miny,maxx,maxy]")));
else
{
if (!args[0]->IsArray())
return ThrowException(Exception::Error(
String::New("Must provide an array of either [x,y] or [minx,miny,maxx,maxy]")));
Local<Array> a = Local<Array>::Cast(args[0]);
uint32_t array_length = a->Length();
if (array_length == 2)
{
double x = a->Get(0)->NumberValue();
double y = a->Get(1)->NumberValue();
double z = 0;
if (!p->this_->forward(x,y,z))
{
std::ostringstream s;
s << "Failed to forward project "
<< a->Get(0)->NumberValue() << "," << a->Get(1)->NumberValue() << " from " << p->this_->source().params() << " to " << p->this_->dest().params();
return ThrowException(Exception::Error(
String::New(s.str().c_str())));
}
Local<Array> a = Array::New(2);
a->Set(0, Number::New(x));
a->Set(1, Number::New(y));
return scope.Close(a);
}
else if (array_length == 4)
{
mapnik::box2d<double> box(a->Get(0)->NumberValue(),
a->Get(1)->NumberValue(),
a->Get(2)->NumberValue(),
a->Get(3)->NumberValue());
if (!p->this_->forward(box))
{
std::ostringstream s;
s << "Failed to forward project "
<< box << " from " << p->this_->source().params() << " to " << p->this_->dest().params();
return ThrowException(Exception::Error(
String::New(s.str().c_str())));
}
Local<Array> a = Array::New(4);
a->Set(0, Number::New(box.minx()));
a->Set(1, Number::New(box.miny()));
a->Set(2, Number::New(box.maxx()));
a->Set(3, Number::New(box.maxy()));
return scope.Close(a);
}
else
return ThrowException(Exception::Error(
String::New("Must provide an array of either [x,y] or [minx,miny,maxx,maxy]")));
}
}