Search code examples
node.jsnode-gyp

How to pass string/integer value from js to c++?


I am using Nodejs c++ addon in my nodejs project. JS calls a method defined in c++ with a string as the parameter. I couldn't get the string in c++. Below is my code in c++:

NAN_METHOD(DBNode::Test){
  printf("Hello\n");
  printf("%s\n", info[0]->ToString());
  printf("%d\n", info[1]->ToNumber());
}

Below is my js code:

const test = require('./build/Release/test.node');
test.test('ssss', 99);

Below is the output:

$ node demo.js 
Hello
?ڄ?C
-272643000

You can see from the above output that the string and integer values are not correctly printed. Is there anything wrong with my code?


Solution

  • Let start from numbers. ToNumber returns value of type Local<Number>. It differs from regular C-like value what printf can digest. First of all you need unwrap Local. It is v8 pointer-like utility class. You can do it with overrided * operator. So *(info[1]->ToNumber()) gives us v8 Number child of Value. But this is not the end of story. Now we can pull good-old int from it (*(info[1]->ToNumber())).Int32Value(). Or you can use the fact Handle ancestors override -> operator too and write like info[1]->ToNumber()->Int32Value().

    String case is harder. V8 uses utf8 strings and you can use String::Utf8Value utility class to get buffer of char from it. *(String::Utf8Value(info[0]->ToString()))

    Usually you do not need it in v8 addons and I suggest you work with v8 objects(like Local, String, Number, etc) in your native code.