开发者

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

开发者 https://www.devze.com 2023-04-04 03:45 出处:网络
I am using WebKitGTK+ in a larger GTKmm/C++ application.I am using JavaScriptCore to interact with the WebKitWebFrame and JSContext within.

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 w开发者_JAVA百科hen 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?


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. 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消