13

I have a function which is ment to take in a string and then pass it to my c++ function add_node()

Handle<Value> Graph::add_node(const v8::Arguments& args)
{
  HandleScope scope;

  Graph* graph = ObjectWrap::Unwrap<Graph>(args.This());
  graph->add_node( args[0]->ToString() );

  std::cout << "In add node \n";
}

However I'm having trouble because all of my arguments are v8 templetes of some sort or another and I cant figure out how to switch between the two. The documentation doesn't state it clearly either.

The compiler is giving me this error

../graph/binding.cc:52:10: error: no matching member function for call to
      'add_node'
  graph->add_node( args[0]->ToString() );
  ~~~~~~~^~~~~~~~
../graph/directed_graph.h:27:7: note: candidate function not viable: no known
      conversion from 'Local<v8::String>' to 'std::string &' (aka
      'basic_string<char> &') for 1st argument;
        void add_node( std::string & currency );

How can I switch between Local<v8::String> and std::string &?

Loourr
  • 4,995
  • 10
  • 44
  • 68

3 Answers3

31

This seems to work well

v8::String::Utf8Value param1(args[0]->ToString());
std::string from = std::string(*param1);

and if you're trying to convert a std::string to a v8::String then do

std::string something("hello world"); 
Handle<Value> something_else = String::New( something.c_str() );
Allen Luce
  • 7,859
  • 3
  • 40
  • 53
Loourr
  • 4,995
  • 10
  • 44
  • 68
  • 5
    Later versions of v8 need a slightly different approach: ```String::NewFromUtf8( isolate, something.c_str() )``` – Richard Jan 29 '17 at 21:36
  • Something for the year 2020? All these answers don't work for node 12 – cybafelo Jan 17 '20 at 15:39
  • yes, when i try this, i get an error error: no matching member function for call to 'ToString' – 2014 Jun 14 '20 at 07:56
2

I don't have that v8 framework on this box, but this

v8::AsciiValue av(args[0]->ToString());
std::basic_string<char> str(av);
graph->add_node(str);

should work, given graph->add_node copies the str.

Solkar
  • 1,228
  • 12
  • 22
0

This works in Mar 2020 (NodeJS v12.16.1):

using v8::Local;
using v8::String;
using v8::NewStringType;

std::string encoded_val = **some_value**;

Local<String> returned_str = String::NewFromUtf8(isolate, encoded_val.c_str(), 
NewStringType::kNormal).ToLocalChecked();
cloaked
  • 13
  • 2