6

i have this function in dll

static COMMANDERDLL_API int InsertCodeBar(const char* pszBuffer);

in my node addon i have this function

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

    Local<Function> cb = Local<Function>::Cast(args[1]);
    Local<String> bar = args[0]->ToString();
    const unsigned argc = 1;
    Local<Value> argv[argc] = { CSGPCommander::InsertCodeBar(bar) };
    cb->Call(isolate->GetCurrentContext()->Global(), argc, argv);
}

when i try compile, node-gyp return error: "cannot convert argument 1 from 'v8::Local' to 'const char *'

how to convert v8::String to const char *?

ZachB
  • 13,051
  • 4
  • 61
  • 89
Matheus Echenique
  • 137
  • 1
  • 2
  • 7

2 Answers2

4

Resolved

create a function ToCString to convert V8::String to const char *

use namespace v8;
const char* ToCString(const String::Utf8Value& value) {
  return *value ? *value : "<string conversion failed>";
}

Usage:

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

    Local<Function> cb = Local<Function>::Cast(args[1]);
    String::Utf8Value str(args[0]);
    const char* bar = ToCString(str);
    const unsigned argc = 1;
    Local<Value> argv[argc] = { CSGPCommander::InsertCodeBar(bar) };
    cb->Call(isolate->GetCurrentContext()->Global(), argc, argv);
}
Matheus Echenique
  • 137
  • 1
  • 2
  • 7
  • 1
    This gives me the error: `error: no matching function for call to ‘v8::String::Utf8Value::Utf8Value(v8::Local&)’ 8 | String::Utf8Value value(str);` – Zane Hitchcox Aug 04 '20 at 23:51
2

Just improve @Matheus's answer:

use namespace v8;
const char* ToCString(Local<String> str) {
  String::Utf8Value value(str);
  return *value ? *value : "<string conversion failed>";
}

And directly use:

const char* bar = ToCString(info[0]);
Yorkie
  • 59
  • 2
  • 1
    A concern of completeness: what is the lifetime value of that char* ? Does it need to be cleaned up on it's own? Does it cease to exist when the underlying Local handle is cleaned up? Because it looks like in your answer you are 1) taking a copy of the Local handle and 2) creating a String::UTF8 on the stack which is going to be cleaned up as value is passed back, risking the car* being cleaned up? – jomamaxx Jan 22 '21 at 20:13