12

我的目标是使用 C 库来构建 Web 应用程序。

我选择了通过使用“SWIG”工具来做到这一点的方式。Swig 工具需要三样东西:

  1. .c定义所有功能的文件。

  2. .i文件也称为接口文件,它正在创建接口以加载我使用extern关键字的 API。

  3. .js用Javascript扩展(文件)编写的APP 。

我使用 SWIG 工具编译和运行这个应用程序来验证.js文件是否正确。该应用程序在 XMING X11 窗口上运行良好。

在编译时_wrap.o,它会创建.o.file 和libFILENAME.so.

现在我想在浏览器页面上运行这个应用程序。

为此,我使用了 webkit clutter port,它为我们提供了 MxLauncher 代码。我正在使用webkit_iweb_view_load_uri(WEBKIT_IWEB_VIEW(view), "filename.html");API 加载我的 html 文件以在我的网页视图上运行该 Javascript。

我正在链接.so编译时创建的。

错误消息:JS CONSOLE:file:///filename.js:ReferenceError:找不到变量:示例

文件名.c

int gcd(int x, int y) `enter code here`{
  int g;
  g = y;
  while (x > 0) {
    g = x;
    x = y % x;
    y = g;
  }
  return g;
}

文件名.i

%module example
extern int    gcd(int x, int y);

文件名.js

x = 42;
y = 105;
g = example.gcd(x,y);

如何让我的目标得以实现?

4

1 回答 1

2

You also need to tell WebKit/JavaScriptCore at runtime about your bindings (this is in addition to linking with filename_wrap.o).

Specifically you need to bind them to the global JavaScript object (in order to invoke per your .js examples). A callback on the WebKit window can be used to get a timely reference to the global JavaScript context, and then you can register your functions onto it.

Adapting this example of hooking into the window-object-cleared signal the code could look similar to this:

/* the window callback - 
     fired when the JavaScript window object has been cleared */
static void window_object_cleared_cb(WebKitWebView  *web_view,
                                     WebKitWebFrame *frame,
                                     gpointer        context,
                                     gpointer        window_object,
                                     gpointer        user_data)
{
  /* Add your classes to JavaScriptCore */
  example_init(context); // example_init generated by SWIG
}


/* ... and in your main application set up */
void yourmainfunc()
{
    ....

    g_signal_connect (G_OBJECT (web_view), "window-object-cleared",
        G_CALLBACK(window_object_cleared_cb), web_view);

    webkit_web_view_load_uri (WEBKIT_WEB_VIEW (web_view), "file://filename.html");

    ...
}

Depending on which branch of SWIG you are using you may need to generate the example_init function yourself (check filename.cxx); for reference here is what an initializer function to register wrapped C functions would look like in SWIG:

int example_init(JSContextRef context) {
  JSObjectRef global = JSContextGetGlobalObject(context);
 ...
  jsc_registerFunction(context, global,  "gcd", _wrap_gcd);
 ...
}

NOTE -- SWIG does not yet officially support JavaScript; the above refers to using the work-in-progress (non-production) SWIG branches.

References:

于 2013-04-01T23:50:22.603 回答