1
Vote

Registering global variable

description

I've wrote 3 methods for registering global variable:
 
// Add these code to public scope of class V8Engine
    virtual void RegisterGlobal(String^ name, Object^ value) abstract;
    virtual void RegisterGlobal(NameValueCollection^ collection) abstract;
    virtual void RegisterGlobal(IEnumerable<KeyValuePair<String^, Object^>>^ collection) abstract;
// Add these code to public scope of class V8EngineImpl
    virtual void RegisterGlobal(String^ name, Object^ value) override;
    virtual void RegisterGlobal(NameValueCollection^ collection) override;
    virtual void RegisterGlobal(IEnumerable<KeyValuePair<String^, Object^>>^ collection) override;
 
// Add these code to V8EngineImpl.cpp
// Register a global variable
void V8EngineImpl::RegisterGlobal(String^ name, Object^ value) {
    v8::HandleScope handleScope;
    v8::Handle<v8::ObjectTemplate> tmpl;
    v8::Handle<v8::ObjectTemplate> protoTmpl;
 
    v8::Context::Scope contextScope(this->objectTemplate->GetContext());
    pin_ptr<const wchar_t> namePtr = PtrToStringChars(name);
    v8::Handle<v8::String> v8Name = v8::String::New((const uint16_t*)namePtr);
    v8::Handle<v8::Value> v8Value = V8ValueWrapper::Unwrap(value);
    this->objectTemplate->GetContext()->Global()->Set(v8Name, v8Value, v8::None);
}
//register mutiple variables in a NameValueCollection
void V8EngineImpl::RegisterGlobal(NameValueCollection^ collection) {
    v8::HandleScope handleScope;
    v8::Handle<v8::ObjectTemplate> tmpl;
    v8::Handle<v8::ObjectTemplate> protoTmpl;
 
    v8::Context::Scope contextScope(this->objectTemplate->GetContext());
    v8::Local<v8::Object> env = this->objectTemplate->GetContext()->Global();
    for each (String^ name in collection) {
        pin_ptr<const wchar_t> namePtr = PtrToStringChars(name);
        v8::Handle<v8::String> v8Name = v8::String::New((const uint16_t*)namePtr);
        v8::Handle<v8::Value> v8Value = V8ValueWrapper::Unwrap(collection[name]);
        env->Set(v8Name, v8Value, v8::None);
    }
}
// same with above, use an enumerator instead of NameValueCollection, such as Dictionary<string, object>
void V8EngineImpl::RegisterGlobal(IEnumerable<KeyValuePair<String^, Object^>>^ collection) {
    v8::HandleScope handleScope;
    v8::Handle<v8::ObjectTemplate> tmpl;
    v8::Handle<v8::ObjectTemplate> protoTmpl;
 
    v8::Context::Scope contextScope(this->objectTemplate->GetContext());
    v8::Local<v8::Object> env = this->objectTemplate->GetContext()->Global();
    for each (KeyValuePair<String^, Object^> item in collection) {
        pin_ptr<const wchar_t> namePtr = PtrToStringChars(item.Key);
        v8::Handle<v8::String> v8Name = v8::String::New((const uint16_t*)namePtr);
        v8::Handle<v8::Value> v8Value = V8ValueWrapper::Unwrap(item.Value);
        env->Set(v8Name, v8Value, v8::None);
    }
}

comments