【问题标题】:Comparing strings passed from arguments比较从参数传递的字符串
【发布时间】:2014-08-06 08:14:07
【问题描述】:

使用 C++ 创建 node.js 插件。我想检查传递的参数是不是hi

节点应用:

addon.Hello("hi");

C++:

if (args[0]->ToString() != "hi") {
  ThrowException(Exception::TypeError(String::New("Sunday morning rain is falling...")));
  return scope.Close(Undefined());
}

但它一直给我错误:

../xxx.cc: 在静态成员函数'static v8::Handle xxx::New(const v8::Arguments&)’: ../xxx.cc:41:29:错误:否 匹配‘operator!=’(操作数类型为‘v8::Local’和 ‘常量字符 [6]’) if (args[0]->ToString() != "hi") { ^

【问题讨论】:

    标签: c++ node.js v8


    【解决方案1】:

    ToString() 返回一个字符串对象。您可以使用 char* foo = *String::Utf8Value(args[0]->ToString()); 之类的内容从中获取 C 字符串。

    【讨论】:

    • 我收到了一个警告:warning: comparison with string literal results in unspecified behaviour [-Waddress]。现在,无论我作为参数传递什么,该语句都会被执行。
    • 这看起来会创建一个悬空指针(虽然我没有使用 V8)。你可能必须先做v8::String::Utf8Value s(args[0]->ToString());,然后再做if (0 == std::strcmp(*s, "hi"))
    • @majidarif 您必须使用提到的@Simple 等C 字符串比较函数。它不是 C++ 字符串。如果您真的想要,请执行以下操作:string foo = string(*String::Utf8Value(args[0]->ToString()));
    • @mscdex 你的意思是“c 字符串”的“0-终止”吗?我认为它实际上只是字节数组
    【解决方案2】:

    是的,我也遇到了同样的问题,这似乎可以编译:

      using namespace std;
    
      v8::String::Utf8Value arg2(args[2]->ToString());
    
      if (strcmp(*arg2, "true") != 0 && strcmp(*arg2, "false") != 0) {
            Nan::ThrowTypeError("Third argument to 'replace-line' must be a string representing whether to find or replace.");
            return;
       }
    
       bool isReplace = strcmp(*arg2, "false") == 0 ? false : true;
    

    我基本上是通过 cmets 从另一个答案得出我的解决方案,有人需要用我在这里所做的实际解决方案更新一个新的答案(我希望如此)。

    【讨论】:

      【解决方案3】:
      #include <string>
      #include <node.h>
      
      String::Utf8Value tmp(args[0]->ToString());
      arg0 = std::string(*tmp);
      //then you can compare string using "== or > or <"
      if(arg0 == "hi")
      {
          ...
      }
      

      【讨论】:

        猜你喜欢
        • 2018-08-05
        • 2015-07-23
        • 1970-01-01
        • 2015-10-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-08-13
        • 1970-01-01
        相关资源
        最近更新 更多