本文整理汇总了C++中StringValue函数的典型用法代码示例。如果您正苦于以下问题:C++ StringValue函数的具体用法?C++ StringValue怎么用?C++ StringValue使用的例子?那么, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了StringValue函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: WriteRawImageFn
// write_raw_image(filename_or_blob, partition)
Value* WriteRawImageFn(const char* name, State* state, int argc, Expr* argv[]) {
char* result = NULL;
Value* partition_value;
Value* contents;
if (ReadValueArgs(state, argv, 2, &contents, &partition_value) < 0) {
return NULL;
}
if (partition_value->type != VAL_STRING) {
ErrorAbort(state, "partition argument to %s must be string", name);
goto done;
}
char* partition = partition_value->data;
if (strlen(partition) == 0) {
ErrorAbort(state, "partition argument to %s can't be empty", name);
goto done;
}
if (contents->type == VAL_STRING && strlen((char*) contents->data) == 0) {
ErrorAbort(state, "file argument to %s can't be empty", name);
goto done;
}
char* filename = contents->data;
if (0 == restore_raw_partition(NULL, partition, filename))
result = strdup(partition);
else {
result = strdup("");
goto done;
}
done:
if (result != partition) FreeValue(partition_value);
FreeValue(contents);
return StringValue(result);
}
示例2: rb_trie_node_walk_bang
static VALUE rb_trie_node_walk_bang(VALUE self, VALUE rchar) {
StringValue(rchar);
TrieState *state;
long string_length ;
TrieChar *char_prefix ;
long p;
Bool result;
Data_Get_Struct(self, TrieState, state);
string_length = (long)NUM2LONG(rb_funcall(rchar, rb_intern("length"), 0));
if (string_length == 1) {
char_prefix = (TrieChar*)RSTRING_PTR(rchar);
for (p = 0; p < RSTRING_LEN(rchar); p++) {
result = trie_state_walk(state, *char_prefix);
if (!result)
return Qnil;
char_prefix++;
}
return self;
}
else
return Qnil;
}
示例3: AssertFn
Value* AssertFn(const char* name, State* state, int argc, Expr* argv[]) {
int i;
for (i = 0; i < argc; ++i) {
char* v = Evaluate(state, argv[i]);
if (v == NULL) {
return NULL;
}
int b = BooleanString(v);
free(v);
if (!b) {
int prefix_len;
int len = argv[i]->end - argv[i]->start;
char* err_src = malloc(len + 20);
strcpy(err_src, "assert failed: ");
prefix_len = strlen(err_src);
memcpy(err_src + prefix_len, state->script + argv[i]->start, len);
err_src[prefix_len + len] = '\0';
free(state->errmsg);
state->errmsg = err_src;
return NULL;
}
}
return StringValue(strdup(""));
}
示例4: mc_decr
VALUE mc_decr(int argc, VALUE *argv, VALUE self) {
memcached_st *mc;
VALUE key, amount;
static memcached_return_t result;
unsigned int offset;
uint64_t value;
Data_Get_Struct(self, memcached_st, mc);
rb_scan_args(argc, argv, "11", &key, &amount);
key = StringValue(key);
if (!use_binary(mc)) key = escape_key(key, NULL);
offset = RTEST(amount) ? NUM2INT(amount) : 1;
result = memcached_decrement(mc, RSTRING_PTR(key), RSTRING_LEN(key), offset, &value);
if (result == MEMCACHED_SUCCESS) {
return LONG2NUM(value);
} else if (result == MEMCACHED_NOTFOUND) {
return Qnil;
} else {
return throw_error(&result);
}
}
示例5: read_data_fn
void
read_data_fn(png_structp png_ptr, png_bytep data, png_size_t length)
{
VALUE io, str;
size_t read_len;
if (png_ptr == NULL)
return;
io = (VALUE)png_get_io_ptr(png_ptr);
str = rb_funcall(io, id_read, 1, INT2FIX(length));
if (NIL_P(str))
rb_raise(rb_eRuntimeError, "Read Error. Reader returned nil.");
StringValue(str);
read_len = RSTRING_LEN(str);
if (read_len != length)
rb_raise(rb_eRuntimeError, "Read Error. Read %d instead of %d bytes.",
(int)read_len, (int)length);
memcpy(data, RSTRING_PTR(str), length);
}
示例6: CommandTMatcher_sorted_matches_for
VALUE CommandTMatcher_sorted_matches_for(int argc, VALUE *argv, VALUE self)
{
// process arguments: 1 mandatory, 1 optional
VALUE abbrev, options;
if (rb_scan_args(argc, argv, "11", &abbrev, &options) == 1)
options = Qnil;
if (NIL_P(abbrev))
rb_raise(rb_eArgError, "nil abbrev");
abbrev = StringValue(abbrev);
abbrev = rb_funcall(abbrev, rb_intern("downcase"), 0);
// check optional options has for overrides
VALUE limit_option = CommandT_option_from_hash("limit", options);
// get unsorted matches
VALUE scanner = rb_iv_get(self, "@scanner");
VALUE paths = rb_funcall(scanner, rb_intern("paths"), 0);
VALUE always_show_dot_files = rb_iv_get(self, "@always_show_dot_files");
VALUE never_show_dot_files = rb_iv_get(self, "@never_show_dot_files");
long path_count = RARRAY_LEN(paths);
match_t *matches = malloc(path_count * sizeof(match_t));
if (!matches)
rb_raise(rb_eNoMemError, "memory allocation failed");
int err;
int thread_count = 1;
#ifdef HAVE_PTHREAD_H
#define THREAD_THRESHOLD 1000 /* avoid the overhead of threading when search space is small */
if (path_count < THREAD_THRESHOLD)
thread_count = 1;
else
thread_count = PROCESSOR_COUNT; // passed in as preprocessor macro
pthread_t *threads = malloc(sizeof(pthread_t) * thread_count);
if (!threads)
rb_raise(rb_eNoMemError, "memory allocation failed");
#endif
thread_args_t *thread_args = malloc(sizeof(thread_args_t) * thread_count);
if (!thread_args)
rb_raise(rb_eNoMemError, "memory allocation failed");
for (int i = 0; i < thread_count; i++) {
thread_args[i].thread_count = thread_count;
thread_args[i].thread_index = i;
thread_args[i].matches = matches;
thread_args[i].path_count = path_count;
thread_args[i].paths = paths;
thread_args[i].abbrev = abbrev;
thread_args[i].always_show_dot_files = always_show_dot_files;
thread_args[i].never_show_dot_files = never_show_dot_files;
#ifdef HAVE_PTHREAD_H
if (i == thread_count - 1) {
#endif
// for the last "worker", we'll just use the main thread
(void)match_thread(&thread_args[i]);
#ifdef HAVE_PTHREAD_H
} else {
err = pthread_create(&threads[i], NULL, match_thread, (void *)&thread_args[i]);
if (err != 0)
rb_raise(rb_eSystemCallError, "pthread_create() failure (%d)", err);
}
#endif
}
#ifdef HAVE_PTHREAD_H
for (int i = 0; i < thread_count - 1; i++) {
err = pthread_join(threads[i], NULL);
if (err != 0)
rb_raise(rb_eSystemCallError, "pthread_join() failure (%d)", err);
}
free(threads);
#endif
if (RSTRING_LEN(abbrev) == 0 ||
(RSTRING_LEN(abbrev) == 1 && RSTRING_PTR(abbrev)[0] == '.'))
// alphabetic order if search string is only "" or "."
qsort(matches, path_count, sizeof(match_t), cmp_alpha);
else
// for all other non-empty search strings, sort by score
qsort(matches, path_count, sizeof(match_t), cmp_score);
VALUE results = rb_ary_new();
long limit = NIL_P(limit_option) ? 0 : NUM2LONG(limit_option);
if (limit == 0)
limit = path_count;
for (long i = 0; i < path_count && limit > 0; i++) {
if (matches[i].score > 0.0) {
rb_funcall(results, rb_intern("push"), 1, matches[i].path);
limit--;
}
}
free(matches);
return results;
}
示例7: write_element
//.........这里部分代码省略.........
break;
}
if (strcmp(cls, "BSON::MinKey") == 0) {
write_name_and_type(buffer, key, 0xff);
break;
}
if (strcmp(cls, "BSON::Timestamp") == 0) {
unsigned int seconds;
unsigned int increment;
write_name_and_type(buffer, key, 0x11);
seconds = NUM2UINT(
rb_funcall(value, rb_intern("seconds"), 0));
increment = NUM2UINT(
rb_funcall(value, rb_intern("increment"), 0));
SAFE_WRITE(buffer, (const char*)&increment, 4);
SAFE_WRITE(buffer, (const char*)&seconds, 4);
break;
}
if (strcmp(cls, "DateTime") == 0 || strcmp(cls, "Date") == 0 || strcmp(cls, "ActiveSupport::TimeWithZone") == 0) {
bson_buffer_free(buffer);
rb_raise(InvalidDocument, "%s is not currently supported; use a UTC Time instance instead.", cls);
break;
}
if(strcmp(cls, "Complex") == 0 || strcmp(cls, "Rational") == 0 || strcmp(cls, "BigDecimal") == 0) {
bson_buffer_free(buffer);
rb_raise(InvalidDocument, "Cannot serialize the Numeric type %s as BSON; only Bignum, Fixnum, and Float are supported.", cls);
break;
}
if (strcmp(cls, "ActiveSupport::Multibyte::Chars") == 0) {
int length;
VALUE str = StringValue(value);
write_name_and_type(buffer, key, 0x02);
length = RSTRING_LENINT(str) + 1;
SAFE_WRITE(buffer, (char*)&length, 4);
write_utf8(buffer, str, 0);
SAFE_WRITE(buffer, &zero, 1);
break;
}
bson_buffer_free(buffer);
rb_raise(InvalidDocument, "Cannot serialize an object of class %s into BSON.", cls);
break;
}
case T_DATA:
{
const char* cls = rb_obj_classname(value);
if (strcmp(cls, "Time") == 0) {
double t = NUM2DBL(rb_funcall(value, rb_intern("to_f"), 0));
long long time_since_epoch = (long long)round(t * 1000);
write_name_and_type(buffer, key, 0x09);
SAFE_WRITE(buffer, (const char*)&time_since_epoch, 8);
break;
}
// Date classes are TYPE T_DATA in Ruby >= 1.9.3
if (strcmp(cls, "DateTime") == 0 || strcmp(cls, "Date") == 0 || strcmp(cls, "ActiveSupport::TimeWithZone") == 0) {
bson_buffer_free(buffer);
rb_raise(InvalidDocument, "%s is not currently supported; use a UTC Time instance instead.", cls);
break;
}
if(strcmp(cls, "BigDecimal") == 0) {
bson_buffer_free(buffer);
rb_raise(InvalidDocument, "Cannot serialize the Numeric type %s as BSON; only Bignum, Fixnum, and Float are supported.", cls);
break;
}
示例8: ApplyPatchFn
// apply_patch(srcfile, tgtfile, tgtsha1, tgtsize, sha1_1, patch_1, ...)
Value* ApplyPatchFn(const char* name, State* state, int argc, Expr* argv[]) {
if (argc < 6 || (argc % 2) == 1) {
return ErrorAbort(state, "%s(): expected at least 6 args and an "
"even number, got %d",
name, argc);
}
char* source_filename;
char* target_filename;
char* target_sha1;
char* target_size_str;
if (ReadArgs(state, argv, 4, &source_filename, &target_filename,
&target_sha1, &target_size_str) < 0) {
return NULL;
}
char* endptr;
size_t target_size = strtol(target_size_str, &endptr, 10);
if (target_size == 0 && endptr == target_size_str) {
ErrorAbort(state, "%s(): can't parse \"%s\" as byte count",
name, target_size_str);
free(source_filename);
free(target_filename);
free(target_sha1);
free(target_size_str);
return NULL;
}
int patchcount = (argc-4) / 2;
Value** patches = ReadValueVarArgs(state, argc-4, argv+4);
int i;
for (i = 0; i < patchcount; ++i) {
if (patches[i*2]->type != VAL_STRING) {
ErrorAbort(state, "%s(): sha-1 #%d is not string", name, i);
break;
}
if (patches[i*2+1]->type != VAL_BLOB) {
ErrorAbort(state, "%s(): patch #%d is not blob", name, i);
break;
}
}
if (i != patchcount) {
for (i = 0; i < patchcount*2; ++i) {
FreeValue(patches[i]);
}
free(patches);
return NULL;
}
char** patch_sha_str = malloc(patchcount * sizeof(char*));
for (i = 0; i < patchcount; ++i) {
patch_sha_str[i] = patches[i*2]->data;
patches[i*2]->data = NULL;
FreeValue(patches[i*2]);
patches[i] = patches[i*2+1];
}
int result = applypatch(source_filename, target_filename,
target_sha1, target_size,
patchcount, patch_sha_str, patches);
for (i = 0; i < patchcount; ++i) {
FreeValue(patches[i]);
}
free(patch_sha_str);
free(patches);
return StringValue(strdup(result == 0 ? "t" : ""));
}
示例9: SetPermFn
Value* SetPermFn(const char* name, State* state, int argc, Expr* argv[]) {
char* result = NULL;
bool recursive = (strcmp(name, "set_perm_recursive") == 0);
int min_args = 4 + (recursive ? 1 : 0);
if (argc < min_args) {
return ErrorAbort(state, "%s() expects %d+ args, got %d", name, argc);
}
char** args = ReadVarArgs(state, argc, argv);
if (args == NULL) return NULL;
char* end;
int i;
int bad = 0;
int uid = strtoul(args[0], &end, 0);
if (*end != '\0' || args[0][0] == 0) {
ErrorAbort(state, "%s: \"%s\" not a valid uid", name, args[0]);
goto done;
}
int gid = strtoul(args[1], &end, 0);
if (*end != '\0' || args[1][0] == 0) {
ErrorAbort(state, "%s: \"%s\" not a valid gid", name, args[1]);
goto done;
}
if (recursive) {
int dir_mode = strtoul(args[2], &end, 0);
if (*end != '\0' || args[2][0] == 0) {
ErrorAbort(state, "%s: \"%s\" not a valid dirmode", name, args[2]);
goto done;
}
int file_mode = strtoul(args[3], &end, 0);
if (*end != '\0' || args[3][0] == 0) {
ErrorAbort(state, "%s: \"%s\" not a valid filemode",
name, args[3]);
goto done;
}
for (i = 4; i < argc; ++i) {
dirSetHierarchyPermissions(args[i], uid, gid, dir_mode, file_mode);
}
} else {
int mode = strtoul(args[2], &end, 0);
if (*end != '\0' || args[2][0] == 0) {
ErrorAbort(state, "%s: \"%s\" not a valid mode", name, args[2]);
goto done;
}
for (i = 3; i < argc; ++i) {
if (chown(args[i], uid, gid) < 0) {
fprintf(stderr, "%s: chown of %s to %d %d failed: %s\n",
name, args[i], uid, gid, strerror(errno));
++bad;
}
if (chmod(args[i], mode) < 0) {
fprintf(stderr, "%s: chmod of %s to %o failed: %s\n",
name, args[i], mode, strerror(errno));
++bad;
}
}
}
result = strdup("");
done:
for (i = 0; i < argc; ++i) {
free(args[i]);
}
free(args);
if (bad) {
free(result);
return ErrorAbort(state, "%s: some changes failed", name);
}
return StringValue(result);
}
示例10: PackageExtractFileFn
// package_extract_file(package_path, destination_path)
// or
// package_extract_file(package_path)
// to return the entire contents of the file as the result of this
// function (the char* returned is actually a FileContents*).
Value* PackageExtractFileFn(const char* name, State* state,
int argc, Expr* argv[]) {
if (argc != 1 && argc != 2) {
return ErrorAbort(state, "%s() expects 1 or 2 args, got %d",
name, argc);
}
bool success = false;
if (argc == 2) {
// The two-argument version extracts to a file.
char* zip_path;
char* dest_path;
if (ReadArgs(state, argv, 2, &zip_path, &dest_path) < 0) return NULL;
ZipArchive* za = ((UpdaterInfo*)(state->cookie))->package_zip;
const ZipEntry* entry = mzFindZipEntry(za, zip_path);
if (entry == NULL) {
fprintf(stderr, "%s: no %s in package\n", name, zip_path);
goto done2;
}
FILE* f = fopen(dest_path, "wb");
if (f == NULL) {
fprintf(stderr, "%s: can't open %s for write: %s\n",
name, dest_path, strerror(errno));
goto done2;
}
success = mzExtractZipEntryToFile(za, entry, fileno(f));
fclose(f);
done2:
free(zip_path);
free(dest_path);
return StringValue(strdup(success ? "t" : ""));
} else {
// The one-argument version returns the contents of the file
// as the result.
char* zip_path;
Value* v = malloc(sizeof(Value));
v->type = VAL_BLOB;
v->size = -1;
v->data = NULL;
if (ReadArgs(state, argv, 1, &zip_path) < 0) return NULL;
ZipArchive* za = ((UpdaterInfo*)(state->cookie))->package_zip;
const ZipEntry* entry = mzFindZipEntry(za, zip_path);
if (entry == NULL) {
fprintf(stderr, "%s: no %s in package\n", name, zip_path);
goto done1;
}
v->size = mzGetZipEntryUncompLen(entry);
v->data = malloc(v->size);
if (v->data == NULL) {
fprintf(stderr, "%s: failed to allocate %ld bytes for %s\n",
name, (long)v->size, zip_path);
goto done1;
}
success = mzExtractZipEntryToBuffer(za, entry,
(unsigned char *)v->data);
done1:
free(zip_path);
if (!success) {
free(v->data);
v->data = NULL;
v->size = -1;
}
return v;
}
}
示例11: main
int
main(int argc, char* argv[])
{
// setting default parameters for PointToPoint links and channels
Config::SetDefault("ns3::PointToPointNetDevice::DataRate", StringValue("10Mbps"));
Config::SetDefault("ns3::PointToPointChannel::Delay", StringValue("10ms"));
Config::SetDefault("ns3::DropTailQueue::MaxPackets", StringValue("20"));
// Read optional command-line parameters (e.g., enable visualizer with ./waf --run=<> --visualize
CommandLine cmd;
cmd.Parse(argc, argv);
// Creating nodes
NodeContainer nodes;
nodes.Create(3); // 3 nodes, connected: 0 <---> 1 <---> 2
// Connecting nodes using two links
PointToPointHelper p2p;
p2p.Install(nodes.Get(0), nodes.Get(1));
p2p.Install(nodes.Get(1), nodes.Get(2));
// Install NDN stack on all nodes
ndn::StackHelper ndnHelper;
ndnHelper.SetDefaultRoutes(true);
ndnHelper.setCsSize(0);
ndnHelper.SetOldContentStore("ns3::ndn::cs::Lru", "MaxSize", "100");
ndnHelper.InstallAll();
// Choosing forwarding strategy
ndn::StrategyChoiceHelper::InstallAll("/myprefix", "/localhost/nfd/strategy/best-route");
ns3::ndn::AppHelper consumerHelper("ns3::ndn::FileConsumerCbr::MultimediaConsumer");
consumerHelper.SetAttribute("AllowUpscale", BooleanValue(true));
consumerHelper.SetAttribute("AllowDownscale", BooleanValue(false));
consumerHelper.SetAttribute("ScreenWidth", UintegerValue(1920));
consumerHelper.SetAttribute("ScreenHeight", UintegerValue(1080));
consumerHelper.SetAttribute("StartRepresentationId", StringValue("auto"));
consumerHelper.SetAttribute("MaxBufferedSeconds", UintegerValue(30));
consumerHelper.SetAttribute("StartUpDelay", StringValue("0.1"));
consumerHelper.SetAttribute("AdaptationLogic", StringValue("dash::player::RateAndBufferBasedAdaptationLogic"));
consumerHelper.SetAttribute("MpdFileToRequest", StringValue(std::string("/myprefix/AVC/BBB-2s.mpd" )));
//consumerHelper.SetPrefix (std::string("/Server_" + boost::lexical_cast<std::string>(i%server.size ()) + "/layer0"));
ApplicationContainer app1 = consumerHelper.Install (nodes.Get(2));
// Producer responsible for hosting the MPD file
ndn::AppHelper mpdProducerHelper("ns3::ndn::FileServer");
// Producer will reply to all requests starting with /myprefix/AVC/ and hosts the mpd file there
mpdProducerHelper.SetPrefix("/myprefix");
mpdProducerHelper.SetAttribute("ContentDirectory", StringValue("/home/someuser/multimediaData"));
mpdProducerHelper.Install(nodes.Get(0)); // install to some node from nodelist
// Producer responsible for hosting the virtual segments
ndn::AppHelper fakeSegmentProducerHelper("ns3::ndn::FakeFileServer");
// Producer will reply to all requests starting with /myprefix/AVC/BBB/ and hosts the virtual segment files there
fakeSegmentProducerHelper.SetPrefix("/myprefix/AVC/BBB");
fakeSegmentProducerHelper.SetAttribute("MetaDataFile", StringValue("dash_dataset_avc_bbb.csv"));
fakeSegmentProducerHelper.Install(nodes.Get(0)); // install to some node from nodelist
ndn::GlobalRoutingHelper ndnGlobalRoutingHelper;
ndnGlobalRoutingHelper.InstallAll();
ndnGlobalRoutingHelper.AddOrigins("/myprefix", nodes.Get(0));
ndn::GlobalRoutingHelper::CalculateRoutes();
Simulator::Stop(Seconds(1000.0));
Simulator::Run();
Simulator::Destroy();
NS_LOG_UNCOND("Simulation Finished.");
return 0;
}
示例12: api_call
/*
* call-seq:
* Win32::API#call(arg1, arg2, ...)
*
* Calls the function pointer with the given arguments (if any). Note that,
* while this method will catch some prototype mismatches (raising a TypeError
* in the process), it is not fulproof. It is ultimately your job to make
* sure the arguments match the +prototype+ specified in the constructor.
*
* For convenience, nil is converted to NULL, true is converted to TRUE (1)
* and false is converted to FALSE (0).
*/
static VALUE api_call(int argc, VALUE* argv, VALUE self){
VALUE v_proto, v_args, v_arg, v_return;
Win32API* ptr;
unsigned long return_value;
int i = 0;
int len;
struct{
unsigned long params[20];
} param;
Data_Get_Struct(self, Win32API, ptr);
rb_scan_args(argc, argv, "0*", &v_args);
v_proto = rb_iv_get(self, "@prototype");
// For void prototypes, allow either no args or an explicit nil
if(RARRAY_LEN(v_proto) != RARRAY_LEN(v_args)){
char* c = StringValuePtr(RARRAY_PTR(v_proto)[0]);
if(!strcmp(c, "V")){
rb_ary_push(v_args, Qnil);
}
else{
rb_raise(rb_eArgError,
"wrong number of parameters: expected %d, got %d",
RARRAY_LEN(v_proto), RARRAY_LEN(v_args)
);
}
}
len = RARRAY_LEN(v_proto);
for(i = 0; i < len; i++){
v_arg = RARRAY_PTR(v_args)[i];
// Convert nil to NULL. Otherwise convert as appropriate.
if(NIL_P(v_arg))
param.params[i] = (unsigned long)NULL;
else if(v_arg == Qtrue)
param.params[i] = TRUE;
else if(v_arg == Qfalse)
param.params[i] = FALSE;
else
switch(ptr->prototype[i]){
case _T_LONG:
param.params[i] = NUM2ULONG(v_arg);
break;
case _T_INTEGER:
param.params[i] = NUM2INT(v_arg);
break;
case _T_POINTER:
if(FIXNUM_P(v_arg)){
param.params[i] = NUM2ULONG(v_arg);
}
else{
StringValue(v_arg);
rb_str_modify(v_arg);
param.params[i] = (unsigned long)StringValuePtr(v_arg);
}
break;
case _T_CALLBACK:
ActiveCallback = v_arg;
v_proto = rb_iv_get(ActiveCallback, "@prototype");
param.params[i] = (LPARAM)NUM2ULONG(rb_iv_get(ActiveCallback, "@address"));;
break;
case _T_STRING:
param.params[i] = (unsigned long)RSTRING_PTR(v_arg);
break;
default:
param.params[i] = NUM2ULONG(v_arg);
}
}
/* Call the function, get the return value */
return_value = ptr->function(param);
/* Return the appropriate type based on the return type specified
* in the constructor.
*/
switch(ptr->return_type){
case _T_INTEGER:
v_return = INT2NUM(return_value);
break;
case _T_LONG:
v_return = ULONG2NUM(return_value);
break;
//.........这里部分代码省略.........
示例13: CallbackFunction
DWORD CallbackFunction(CALLPARAM param, VALUE callback)
{
VALUE v_proto, v_return, v_proc, v_retval;
VALUE argv[20];
int i, argc;
char *a_proto;
char *a_return;
if(callback && !NIL_P(callback)){
v_proto = rb_iv_get(callback, "@prototype");
a_proto = RSTRING_PTR(v_proto);
v_return = rb_iv_get(callback, "@return_type");
a_return = RSTRING_PTR(v_return);
v_proc = rb_iv_get(callback, "@function");
argc = RSTRING_LEN(v_proto);
for(i=0; i < RSTRING_LEN(v_proto); i++){
argv[i] = Qnil;
switch(a_proto[i]){
case 'L':
argv[i] = ULONG2NUM(param.params[i]);
break;
case 'P':
if(param.params[i])
argv[i] = rb_str_new2((char *)param.params[i]);
break;
case 'I':
argv[i] = INT2NUM(param.params[i]);
break;
default:
rb_raise(cAPIProtoError, "Illegal prototype '%s'", a_proto[i]);
}
}
v_retval = rb_funcall2(v_proc, rb_intern("call"), argc, argv);
/* Handle true and false explicitly, as some CALLBACK functions
* require TRUE or FALSE to break out of loops, etc.
*/
if(v_retval == Qtrue)
return TRUE;
else if(v_retval == Qfalse)
return FALSE;
switch (*a_return) {
case 'I':
return NUM2INT(v_retval);
break;
case 'L':
return NUM2ULONG(v_retval);
break;
case 'S':
return (unsigned long)RSTRING_PTR(v_retval);
break;
case 'P':
if(NIL_P(v_retval)){
return 0;
}
else if(FIXNUM_P(v_retval)){
return NUM2ULONG(v_retval);
}
else{
StringValue(v_retval);
rb_str_modify(v_retval);
return (unsigned long)StringValuePtr(v_retval);
}
break;
}
}
return 0;
}
示例14: InterposeProperty
bool
InterposeProperty(JSContext* cx, HandleObject target, const nsIID* iid, HandleId id,
MutableHandle<JSPropertyDescriptor> descriptor)
{
// We only want to do interpostion on DOM instances and
// wrapped natives.
RootedObject unwrapped(cx, UncheckedUnwrap(target));
const js::Class* clasp = js::GetObjectClass(unwrapped);
bool isCPOW = jsipc::IsWrappedCPOW(unwrapped);
if (!mozilla::dom::IsDOMClass(clasp) &&
!IS_WN_CLASS(clasp) &&
!IS_PROTO_CLASS(clasp) &&
clasp != &OuterWindowProxyClass &&
!isCPOW) {
return true;
}
XPCWrappedNativeScope* scope = ObjectScope(CurrentGlobalOrNull(cx));
MOZ_ASSERT(scope->HasInterposition());
nsCOMPtr<nsIAddonInterposition> interp = scope->GetInterposition();
InterpositionWhitelist* wl = XPCWrappedNativeScope::GetInterpositionWhitelist(interp);
// We do InterposeProperty only if the id is on the whitelist of the interpostion
// or if the target is a CPOW.
if ((!wl || !wl->has(JSID_BITS(id.get()))) && !isCPOW)
return true;
JSAddonId* addonId = AddonIdOfObject(target);
RootedValue addonIdValue(cx, StringValue(StringOfAddonId(addonId)));
RootedValue prop(cx, IdToValue(id));
RootedValue targetValue(cx, ObjectValue(*target));
RootedValue descriptorVal(cx);
nsresult rv = interp->InterposeProperty(addonIdValue, targetValue,
iid, prop, &descriptorVal);
if (NS_FAILED(rv)) {
xpc::Throw(cx, rv);
return false;
}
if (!descriptorVal.isObject())
return true;
// We need to be careful parsing descriptorVal. |cx| is in the compartment
// of the add-on and the descriptor is in the compartment of the
// interposition. We could wrap the descriptor in the add-on's compartment
// and then parse it. However, parsing the descriptor fetches properties
// from it, and we would try to interpose on those property accesses. So
// instead we parse in the interposition's compartment and then wrap the
// descriptor.
{
JSAutoCompartment ac(cx, &descriptorVal.toObject());
if (!JS::ObjectToCompletePropertyDescriptor(cx, target, descriptorVal, descriptor))
return false;
}
// Always make the property non-configurable regardless of what the
// interposition wants.
descriptor.setAttributes(descriptor.attributes() | JSPROP_PERMANENT);
if (!JS_WrapPropertyDescriptor(cx, descriptor))
return false;
return true;
}
示例15: Literal
Value* Literal(const char* name, State* state, int argc, Expr* argv[]) {
return StringValue(strdup(name));
}