简体   繁体   English

回调需要const函数,如何传递对象的实例成员

[英]Callback requires const function, how to pass instance member of object

I am using WebKitGTK+ in a larger GTKmm/C++ application. 我在更大的GTKmm / C ++应用程序中使用WebKitGTK +。 I am using JavaScriptCore to interact with the WebKitWebFrame and JSContext within. 我正在使用JavaScriptCore与WebKitWebFrame和JSContext进行交互。

I am stuck now as I need to interact with a GTK GUI component when a javascript function is called. 我现在陷入困境,因为我需要在调用javascript函数时与GTK GUI组件进行交互。 To this end I found the JSObjectMakeFunctionWithCallback function. 为此我找到了JSObjectMakeFunctionWithCallback函数。

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: 必须使用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. 所以一切正常,除了我需要回调中的对象实例来回到我需要操作的GUI组件。

There are tons of similar questions on SO but most focus on passing the object instance into the callback. 在SO上有很多类似的问题,但大多数都专注于将对象实例传递给回调。 I can not see a way of doing that with this API. 我无法通过此API看到这样做的方法。

Any ideas? 有任何想法吗?

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: 一个常见的解决方案是创建一个保存对象实例的中间全局自由函数:

JSValueRef ClickCallback(...)
{
  Foo & obj = getInstance(); // implement this somehow
  return obj.click(...);
}

Alternatively, you can make this a static member function of your GUI class. 或者,您可以将其设置为GUI类的静态成员函数。 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. 重点是您必须单独获取实例引用,并且如果必须将普通函数指针传递给API,则自己调用成员函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM