pmed / v8pp

Bind C++ functions and classes into V8 JavaScript engine
http://pmed.github.io/v8pp/
Other
886 stars 118 forks source link

How can i pass a JS Date object? #184

Closed StefanWoe closed 1 year ago

StefanWoe commented 1 year ago

In a JS i want to create a Date() object and then pass this to a C++ Function that is called via v8pp. Is that possible? How?

Best regards

pmed commented 1 year ago

Hi,

there is no special data conversion for JavaScript Date in v8pp. I think a C++ function may accept a generic v8::Value parameter, to handle it in a proper way.

StefanWoe @.***> schrieb am Fr., 19. Aug. 2022, 19:02:

In a JS i want to create a Date() object and then pass this to a C++ Function that is called via v8pp. Is that possible? How?

Best regards

— Reply to this email directly, view it on GitHub https://github.com/pmed/v8pp/issues/184, or unsubscribe https://github.com/notifications/unsubscribe-auth/AAISAURQPB5IZIDGDV6X4ODVZ642PANCNFSM57BL3PCQ . You are receiving this because you are subscribed to this thread.Message ID: @.***>

StefanWoe commented 1 year ago

Thanks for the hint, the following code works:

void myFunc(v8::Isolate *ptr, v8::Local<v8::Value> params) 
{

  if(params->IsDate()) {
    v8::Date *date = v8::Date::Cast(*params); 
    double millisSinceEpoch = date->ValueOf();
    std::time_t t = static_cast<time_t>(millisSinceEpoch/1000);
    ...
  }
}

JS: 
    var date = new Date();
    myFunc(date);
uniqss commented 1 year ago

Does this works with Set? this is my code, using the v8::value, but still not working. if (si->IsSet()) return true, but I just don't know how to get the result.

static void test_param_set_string(v8::Isolate* isolate, v8::Local<v8::Value> si, const v8::Local<v8::Value>& crsi)
{
    P_JS_CALL_CPP_FUNC;
    if (si->IsSet())
    {
        cout << "set working" << endl;
        v8::Set* pset = v8::Set::Cast(*si);
        auto set = v8pp::convert<std::set<std::string>>::from_v8(isolate, si);

        cout << pset->Size() << endl;
        for (uint32_t i = 0, count = pset->Size(); i < count; ++i)
        {
            v8::Local<v8::Value> item = pset->Get(isolate->GetCurrentContext(), i).ToLocalChecked();
            if (item->IsNullOrUndefined())
            {
                cout << "not string" << endl;
                continue;
            }
            auto val = v8pp::convert<std::string>::from_v8(isolate, item);
            cout << val << " " << endl;
        }
        cout << endl;
    }
    else
    {
        cout << "set not working" << endl;
    }

js code:

    const set_str1 = new Set(["banana", "apple", "peach"]);
    const set_str2 = new Set(["hello", "world", "kitty"]);
    dlog("set_str1:", set_str1);
    test_param_set_string(set_str1, set_str2);
pmed commented 1 year ago

Hi,

It makes sense, to support Set, Map JavaScript types natively, since recent V8 versions have support of them.

As usual, PRs are very welcome!