javascript扩展,在webapp中使用基于C的API(混乱)

use*_*227 12 javascript swig webkit javascript-events clutter

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

我已经通过使用"SWIG"工具选择了这样做的方法.Swig工具需要三件事

1) .c file which defines all the functions.

2) .i file also called interface file which is creating the
interface to load the APIs wherin I used the extern keyword.

3) APP written in javascript extension (.js file).
Run Code Online (Sandbox Code Playgroud)

我使用SWIG工具编译并运行此应用程序以验证.js文件是否正确.应用程序在XMING X11窗口上运行正常.

在编译时,它创建_wrap.o,.o文件和libFILENAME.so

现在我想在浏览器页面上运行此应用程序.

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

我正在编译在编译时创建的.so.

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

FILENAME.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;
}
Run Code Online (Sandbox Code Playgroud)

filename.i

%module example
extern int    gcd(int x, int y);
Run Code Online (Sandbox Code Playgroud)

filename.js

x = 42;
y = 105;
g = example.gcd(x,y);
Run Code Online (Sandbox Code Playgroud)

如何实现我的目标?

hum*_*tim 2

您还需要在运行时告诉 WebKit/JavaScriptCore 您的绑定(这是除了与 filename_wrap.o 链接之外的)。

具体来说,您需要将它们绑定到全局 JavaScript 对象(以便根据您的 .js 示例进行调用)。WebKit 窗口上的回调可用于及时引用全局 JavaScript 上下文,然后您可以将函数注册到其上。

调整这个挂钩到信号的示例window-object-cleared,代码可能类似于以下内容:

/* 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");

    ...
}
Run Code Online (Sandbox Code Playgroud)

根据您使用的 SWIG 分支,您可能需要example_init自己生成函数(检查 filename.cxx);这里供参考的是SWIG 中注册包装 C 函数的初始化函数的样子:

int example_init(JSContextRef context) {
  JSObjectRef global = JSContextGetGlobalObject(context);
 ...
  jsc_registerFunction(context, global,  "gcd", _wrap_gcd);
 ...
}
Run Code Online (Sandbox Code Playgroud)

注意——SWIG 尚未正式支持 JavaScript;上述指的是使用正在进行的(非生产)SWIG 分支。

参考: