samedi 21 août 2021

how pass cstring to nodejs by v8.h

I want to return the callback function result to js by v8.h.

But the g_isolate.GetCurrentContext() return NULL.

The trafficASyncRequestCall function from traffic_common_api.h needs given callback function type.

The nodejs version is 10.16.2,at windows10 VS2017

#include <v8.h>
#include <node.h>
#include <node_buffer.h>
#include "traffic_common_api.h"

using namespace std;
using namespace v8;
using namespace node;

Local<v8::Function> g_callbackAsyncToNodejs;
Isolate* g_isolate;

static void g_callbackAsync(TrafficNetworkResponseMessage& response)
{
    cJSON* json = cJSON_CreateObject();
    cJSON_AddItemToObject(json, "code", cJSON_CreateNumber(response.network_error_code));
    cJSON * item = cJSON_CreateObject();
    cJSON_AddItemToObject(item, "pbLen", cJSON_CreateNumber(response.pbRequestBody.len));
    cJSON_AddItemToObject(item, "pbData",cJSON_CreateString((char*)response.pbRequestBody.data));
    cJSON_AddItemToObject(json, "data", item);
    const unsigned argc = 1;
    Local<Value> argv[argc] = {String::NewFromUtf8(g_isolate, cJSON_Print(json))};
    g_callbackAsyncToNodejs->Call(g_isolate->GetCurrentContext()->Global(), argc, argv);

    cJSON_Delete(json);
}

void asyncRunCall(const FunctionCallbackInfo<Value>& args) 
{
    g_isolate = args.GetIsolate();
    Local<v8::Value> value0 = Local<v8::Value>::Cast(args[0]);
    g_callbackAsyncToNodejs = Local<v8::Function>::Cast(args[1]);
    v8::String::Utf8Value serverKeyUtf80(g_isolate, value0);
    string messageInfo = string(*serverKeyUtf80);
    int ret = trafficASyncRequestCall(messageInfo, g_callbackAsync);
    args.GetReturnValue().Set(Int32::New(g_isolate, ret));
}

NODE_MODULE_INIT()
{
    Isolate* isolate = context->GetIsolate();
    NODE_SET_METHOD(exports, "asyncRunCall", asyncRunCall);
}

Aucun commentaire:

Enregistrer un commentaire