回调需要const函数,如何传递对象的实例成员
我在更大的 GTKmm/C++ 应用程序中使用 WebKitGTK+。我正在使用 JavaScriptCore 与其中的 WebKitWebFrame 和 JSContext 进行交互。
我现在陷入困境,因为调用 javascript 函数时我需要与 GTK GUI 组件交互。为此,我找到了 JSObjectMakeFunctionWithCallback 函数。
JSStringRef str = JSStringCreateWithUTF8CString("ClickCallback");
JSObjectRef func = JSObjectMakeFunctionWithCallback(m_jsRef, str, ClickCallback);
JSObjectSetProperty(m_jsRef, JSContextGetGlobalObject(m_jsRef), str, func, kJSPropertyAttributeNone, NULL);
JSStringRelease(str);
其中回调必须使用 def: 定义为静态函数,
static JSValueRef ClickCallback(JSContextRef ctx, JSObjectRef func, JSObjectRef self, size_t argc, const JSValueRef argv[], JSValueRef* exception)
所以一切正常,除了我需要回调中的对象实例来返回我需要操作的 GUI 组件。
关于 SO 有很多类似的问题,但大多数都集中在将对象实例传递到回调中。我看不到使用此 API 执行此操作的方法。
有什么想法吗?
I am using WebKitGTK+ in a larger GTKmm/C++ application. I am using JavaScriptCore to interact with the WebKitWebFrame and JSContext within.
I am stuck now as I need to interact with a GTK GUI component when a javascript function is called. To this end I found the JSObjectMakeFunctionWithCallback function.
JSStringRef str = JSStringCreateWithUTF8CString("ClickCallback");
JSObjectRef func = JSObjectMakeFunctionWithCallback(m_jsRef, str, ClickCallback);
JSObjectSetProperty(m_jsRef, JSContextGetGlobalObject(m_jsRef), str, func, kJSPropertyAttributeNone, NULL);
JSStringRelease(str);
Where the callback must be defined as a static function with def:
static JSValueRef ClickCallback(JSContextRef ctx, JSObjectRef func, JSObjectRef self, size_t argc, const JSValueRef argv[], JSValueRef* exception)
So everything is working except I need my object instance in the callback to get back at the GUI component I need to manipulate.
There are tons of similar questions on SO but most focus on passing the object instance into the callback. I can not see a way of doing that with this API.
Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
回调必须是指向自由函数的指针,因此再多的魔法也无法让您直接传递成员函数。一种常见的解决方案是创建一个保存对象实例的中间全局自由函数:
或者,您可以将其设为 GUI 类的静态成员函数。要点是,如果必须向 API 传递普通函数指针,则必须单独获取实例引用并自己调用成员函数。
The callback is required to be a pointer to a free function, so no amount of magic can get you to pass a member function directly. One common solution is to make an intermediate global free function that holds the object instance:
Alternatively, you can make this a static member function of your GUI class. The main point is that you must obtain the instance reference separately and call the member function yourself if you have to pass a plain function pointer to your API.