Search code examples
c++v8embedded-v8

How to stringify an Integer in V8?


I'm trying to stringify an integer in v8.

The nearest I've come to success so far is using String::Concat. I tried writing this method (in a node.js 9.11.1 native addon), but it doesn't compile.

void Method(const FunctionCallbackInfo<Value> &args) {
  Isolate *isolate = args.GetIsolate();

  const int num = 42;
  args.GetReturnValue().Set(
      String::Concat(String::NewFromUtf8(isolate, "The num is: "),
                      Integer::New(isolate, num)));
}

The compile error is:

'=': cannot convert from 'v8::Integer *' to 'v8::String *volatile '

I haven't been able to figure out the right parts of the v8 API to make use of to format an integer into a string. I'm (perhaps obviously) not familiar with the v8 API, and I'm having trouble finding good examples to learn from.

I was going by the answer to this question: How to convert an Integer to a String in V8? although it appears to be stale compared to the modern v8 API. The example appears to be pre-"isolate" for example.

I was under the impression that Concat would accept this because in JavaScript it just coerces the int to a string (that seems to be the gist of that question I referenced). But I guess maybe I have to be explicit about that when coding with v8?

I'm sure it's something simple I'm missing. I'd appreciate someone suggesting a better way.


Solution

  • Try calling ToString on the Integer you just created.

    See the function declaration here: https://chromium.googlesource.com/v8/v8/+/6.5.254.41/include/v8.h#2333

    The magic where "JavaScript just coerces the int" must be implemented somewhere -- namely, on the C++ side, where all such conversions are done manually ;-)