gpt4 book ai didi

c++ - 从 v8 函数中获取默认参数的最短方法(单行)?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:00:11 24 4
gpt4 key购买 nike

我已经有很长一段时间没有使用 C++ 了,甚至更久没有开始研究硬类型了。我只是在寻找一个工作 one liner 来从 v8 获取参数,或者在未提供参数时获取默认值。

v8::String::Utf8Value arg0(args[0]);
v8::String::Utf8Value arg1(args[1]);
v8::String::Utf8Value arg2(args[2]);
const char *username = (args.Length() > 0) ? *arg0 : "";
const char *password = (args.Length() > 1) ? *arg1 : "";
const char *service = (args.Length() > 2) ? *arg2 : "login";

输出:

func(); // { username: "", password: "", service: "login" }func('1'); // { username: "1", password: "", service: "login" }func('1', '2'); // { username: "1", password: "2", service: "login" }func('a', 'b', 'c'); // { username: "a", password: "b", service: "c" }

Unfortunately, the following close-to-ideal solution doesn't work for me (any ideas why?):

const char *username = (args.Length() > 0) ? *v8::String::Utf8Value(args[0]->ToString()) : "";
const char *password = (args.Length() > 1) ? *v8::String::Utf8Value(args[1]->ToString()) : "";
const char *service = (args.Length() > 2) ? *v8::String::Utf8Value(args[2]->ToString()) : "login";

最佳答案

Vyacheslav Egorov 用他的评论指出了这一点,当我访问该字符串时,它已被销毁。最终我最终使用了:

char *get(v8::Local<v8::Value> value, const char *fallback = "") {
if (value->IsString()) {
v8::String::AsciiValue string(value);
char *str = (char *) malloc(string.length() + 1);
strcpy(str, *string);
return str;
}
char *str = (char *) malloc(strlen(fallback) + 1);
strcpy(str, fallback);
return str;
}

使用示例:

v8::Handle<v8::Value> myMethod(const v8::Arguments &args) {
char *username = get(args[0], "user");
char *password = get(args[1], "pass");

...
}

关于c++ - 从 v8 函数中获取默认参数的最短方法(单行)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10507323/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com