- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我正在使用 v8 为我的 C++ 应用程序创建一个 javascript 接口(interface),但遇到了函数回调问题。
我有一个对象模板,它有对象“更新”的 setter 和 getter,它只是设置/获取 setter 和 getter 都可以访问的对象句柄(参见“我试过的东西”。)实例化一个对象在此对象模板中称为“world”的全局上下文中。然后运行脚本,将“world.update”设置为具有基本输出消息的函数。该程序然后获取更新功能并调用它,它完全按预期工作 - 打印一些输出。然后程序再次获取更新函数,但更新函数现在是一个字符串——原始调用的输出。尝试调用它会导致异常。
代码:
#include <iostream>
#include <fstream>
#include <string>
#include <v8.h>
using namespace v8;
std::string readFile(std::string fname) {
std::ifstream finput(fname);
std::string filestr((std::istreambuf_iterator<char>(finput)),
std::istreambuf_iterator<char>());
return filestr;
}
Handle<Value> print(const Arguments& args) {
String::AsciiValue str(args[0]);
std::cout << *str;
HandleScope scope;
return scope.Close(Undefined());
}
class FuncWrapper {
public:
Handle<Function> func;
};
Handle<Value> getWorldUpdate(Local<String> property, const AccessorInfo &info) {
std::cout << "Get update() [" << *String::AsciiValue(property) << "]\n";
Local<Object> self = info.Holder();
Local<External> wrap = Local<External>::Cast(self->GetInternalField(0));
FuncWrapper *fw = static_cast<FuncWrapper*>(wrap->Value());
return fw->func;
}
void setWorldUpdate(Local<String> property, Local<Value> value, const AccessorInfo& info) {
std::cout << "Set update() [" << *String::AsciiValue(property) << "]\n";
Local<Object> self = info.Holder();
Local<External> wrap = Local<External>::Cast(self->GetInternalField(0));
FuncWrapper *fw = static_cast<FuncWrapper*>(wrap->Value());
//Accessor info could be used to get the class here
fw->func = Handle<Function>::Cast(value);
}
int main() {
// Create a stack-allocated handle scope.
HandleScope handle_scope;
//Add stuff
Handle<ObjectTemplate> globalScope = ObjectTemplate::New();
globalScope->Set(String::New("print"), FunctionTemplate::New(print));
Handle<ObjectTemplate> worldTmpl = ObjectTemplate::New();
worldTmpl->SetInternalFieldCount(1);
worldTmpl->SetAccessor(String::New("update"), getWorldUpdate, setWorldUpdate);
// Create a new context.
Handle<Context> context = Context::New(NULL, globalScope);
// Enter the created context for compiling
Context::Scope context_scope(context);
Handle<Object> global = context->Global();
Handle<Object> world = worldTmpl->NewInstance();
FuncWrapper worldUpdateFunc;
world->SetInternalField(0, External::New((void*)&worldUpdateFunc));
global->Set(String::New("world"), world);
// Compile the source code.
Handle<Script> script = Script::Compile(String::New(readFile("main.js").c_str()));
// Run the script to get the result.
script->Run();
v8::TryCatch try_catch;
Handle<Function> updateFunc = Handle<Function>::Cast(world->Get(String::New("update")));
updateFunc->Call(updateFunc, 0, NULL);
if (try_catch.HasCaught()) {
String::AsciiValue asciistr(try_catch.Message()->Get());
std::cout << "Caught1: " << *asciistr << "\n";
return -1;
}
//Re-calling. Has the same effect as calling worldUpdateFunc.func
updateFunc = Handle<Function>::Cast(world->Get(String::New("update")));
updateFunc->Call(updateFunc, 0, NULL);
if (try_catch.HasCaught()) {
String::AsciiValue asciistr(try_catch.Message()->Get());
std::cout << "Caught2: " << *asciistr << "\n";
return -1;
}
return 0;
}
脚本(main.js):
"use strict";
world.update = function() {
print("Did a world.update()\n");
}
输出:
Set update() [update]
Get update() [update]
Did a world.update()
Get update() [update]
Caught2: Uncaught TypeError: Did a world.update()
is not a function
没有对象模板(即只有一个没有 getter/setter 组合的 javascript 中的常规对象)程序运行良好,但我希望能够使用它来让脚本管理回调。
为什么会发生这种情况,我做错了什么?
我尝试过的事情:
最佳答案
问题是函数句柄指向的对象正在被删除。
解决方案是简单地包装一个 Persistent 而不是一个句柄,然后调用 Persistent::New() 来创建一个新的函数实例。
class FuncWrapper {
public:
Persistent<Function> func;
};
...
void setWorldUpdate(Local<String> property, Local<Value> value, const AccessorInfo& info) {
...
fw->func = Persistent<Function>::New(Local<Function>::Cast(value));
}
感谢 v8-users group 的人们帮助我solve this !
关于javascript - 函数的Setter/Getter在调用函数时将函数转换为字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19202721/
如果您有一个具有一些普通 get/set 属性的类,是否有任何理由在类方法中使用 getter,或者您应该只使用私有(private)成员变量?我认为关于setter(验证逻辑?)可能会有更多争论,但
我是 Android 编程的新手(~ 2 个月)有必要为几十个不同的变量设置 getter 吗? 例如—— //Yes I realise that this isn't 'dozens' publi
我是VUEX新手,在学习VUEX的同时搭建了一个测试应用。我已将我的 VUEX 存储拆分为多个模块,每个模块都有自己的 getter.js 文件。 Getters、 Action 、突变被导入到每个模
我有一项服务正在加载我想在多个组件之间共享的基本系统信息。 如果我在 getter 中创建一个 getter 方法 this 如果我不在服务中使用双箭头,则 getter 中的 this 成为组件的
tl;博士 如何从参数化的 getter 访问其他 getter? 通常可以使用this.myGetter ;但是参数化的 getter 被实现为箭头函数,其中 this未定义。 在 Pinia 中处
我第一次尝试做一些 OOP,这不是简单的练习,而是用 java 编写一个程序来存储有关人员的信息(如通讯录)。下面是我正在开发的名为 Person 的类的片段。 Person 将在将来的某个时间被其他
我在某处看到类似下面的内容,想知道它是什么意思。我知道他们是getter和setter,但是想知道为什么字符串Type是这样定义的。谢谢你帮助我。 public string Type { get;
Public class Example { private int number; public Example(int number){ this.number =
getter 应该只返回对象吗: public MyObject getMyObject() { return myObject; } 或者它应该复制它返回的对象并返回该副本? public
我目前正在处理大量数据输入,包括很多值,我希望在 getter 中接收这些值以供以后使用。 在编写了一些方法之后,我想知道仅使用一个 get 方法是否是一个更好的主意,并使用一个包含所有可能值的枚举类
我正在使用新的 Class Public Field Declarations可用 Chrome 72我遇到了这种真正奇怪的行为: class Extended { property = 5; }
我有一个这样的表达式 setter/getter : var expression = () => SomeInstance.Nr; 它被传递到一个方法中: public void AddExpres
我的一个类(class)中有以下 getter: get password(){ if(this._public) return null; var text = ""
我已经设法测试了与其他代码隔离的 Vuex getter。当 getter 依赖于其他 getter 时,我现在面临一些问题,请参见以下示例: getters.js export const gett
有时我的任务是查找 getter 返回的值中的某些嵌套 getter 是否具有某些属性。经典的 C++ 会是这样的: for (const auto& label: labels) for (co
我有一个像这样的基类“Parent”: using System; using System.Collections.Generic; using System.Text; namespace Con
我一直在努力了解 getter 和 setter,但没有深入了解。我读过 JavaScript Getters and Setters和 Defining Getters and Setters只是没
考虑一个简单的 Vue 博客: 我使用 Vuex 作为我的数据存储,我需要设置两个 getters :一个 getPost getter,用于通过 ID 检索 post,以及一个 listFeatur
我有一个 VueX 商店,有两个模块,user.js 和merchant.js,顶层是index.js。 user.js 中的 getter 是: 重构 const getters = { s
我正在尝试向 jsp 添加一个复选框以在进入站点之前接受条款和条件。尽管我有一个 getter 方法并且没有看到任何拼写错误,但我一直收到关于没有 getter 方法的相同错误。我不明白我错过了什么。
我是一名优秀的程序员,十分优秀!