简体   繁体   中英

How to convert v8::String to const char *

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 *?

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);
}

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]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM