Hello everyone,
I am struggling wrapping and unwrapping the c++ object (MYCLASS) . below is the sample code i have written for my exact requirement:
void Update_Rotation(const v8::FunctionCallbackInfo<v8::Value>& info);
class MYCLASS {
public:
Point(D_TYPE1 *par1) : rotate(par1) { }
D_TYPE1 *rotate;
void run_script()
{
v8::V8::InitializeICUDefaultLocation(argv);
v8::V8::InitializeExternalStartupData(argv);
std::unique_ptr<v8::Platform> platform = v8::platform::NewDefaultPlatform();
v8::V8::InitializePlatform(platform.get());
v8::V8::Initialize();
v8::Isolate::CreateParams create_params;
create_params.array_buffer_allocator = v8::ArrayBuffer::Allocator::NewDefaultAllocator();
v8::Isolate* isolate = v8::Isolate::New(create_params);
v8::Isolate::Scope isolate_scope(isolate);
v8::Isolate::Scope isolate_scope(isolate);
// Create a stack-allocated handle scope.
v8::HandleScope handle_scope(isolate);
// Create a template for the global object.
v8::Handle<v8::ObjectTemplate> global = v8::ObjectTemplate::New(isolate);
/* Here the internal field count is set to 1 which means the object has one internal field, with an index of 0, that points to a C++ object.*/
global->SetInternalFieldCount(1);
// Bind the 'update_rotation' function
global->Set(v8::String::NewFromUtf8(isolate, "update_rotation", v8::NewStringType::kNormal).ToLocalChecked(),
v8::FunctionTemplate::New(isolate, Update_Rotation));
// Create a new context.
v8::Local<v8::Context> context = v8::Context::New(isolate, NULL, global);
//Persistent<Context> context = v8::Context::New(isolate, NULL, global, nullptr);
// Enter the context for compiling and running the script.
v8::Context::Scope context_scope(context);
Local<Object> obj = global->NewInstance(context).ToLocalChecked();
obj->SetInternalField(0, External::New(isolate, this));
/* My JS script */
v8::Local<v8::String> source = v8::String::NewFromUtf8(isolate, "var rotate_status = update_rotation();",v8::NewStringType::kNormal).ToLocalChecked();
//exception handler
v8::TryCatch try_catch(isolate);
printf("Script : compilation started\n");
// Compile the source code.
v8::Local<v8::Script> script = v8::Script::Compile(context, source).ToLocalChecked();
printf("Script : compilation compilation done\n");
printf("Script : Running started\n");
// Run the script to get the result.
v8::Local<v8::Value> result = script->Run(context).ToLocalChecked();
}
};
void Update_Rotation(const v8::FunctionCallbackInfo<v8::Value>& info) {
Local<Object> self = info.Holder();
Local<External> wrap = Local<External>::Cast(self->GetInternalField(0));
void* ptr = wrap->Value();
MYCLASS* temp_sp = static_cast<MYCLASS*>(ptr); //--> Here i am always getting null pointer
D_TYPE1 *rotate_ptr = static_cast<Point*>(ptr)->rotate;
rotate_ptr->Update();
}
int main()
{
D_TYPE1 *sample_rotate_obj = new D_TYPE1();
MYCLASS test_obj(sample_rotate_obj);
test_obj.run_script();
}
Can anyone plz suggest how to fix it to get valid pointer to my object?
Thanks in advance ...
Regards
Sudheer