使用MinGW/GCC在C++语言中嵌入JavaScript脚本引擎SpiderMonkey

转自行者的足迹http://blog.ccidnet.com/blog-htm-do-showone-uid-36246-type-blog-itemid-106110.html

使用MinGW/GCC在C++语言中嵌入JavaScript脚本引擎SpiderMonkey

SpiderMonkey是Mozilla项目组的javascript解释引擎,是用c编写的,可惜我下载的1.5版SpiderMonkey后,搞了半天也没搞明白怎么在MingGW下编译,用VC6编译却很顺利,于是尝试用MinGW/GCC调用VC动态库,找到了一篇网上的文章:
    http://wyw.dcweb.cn/dllfaq.htm
就是讲这个话题,对照文章里面使用pexports+sed的方法,连接虽然成功了,但是在运行的时候,居然提示找不到DLL中导出的连接符!一看看提示就明白了,MinGW/GCC调用方要求多一个下划线!而实际的DLL导出符表却缺少这个下划线!那篇文章的E文看的不是很明白,好像和里面说的正好相反。后来参考了
    http://www.cppblog.com/zuroc/archive/2006/01/19/2895.aspx
里面讲得的方法,修正了第一篇文章中使用dlltool的命令,命令如下:
    pexports js32.dll > js32.def (生成def文件)
    dlltool --dllname js32.dll --def js32.def ---output-lib libjsdll32.a (生成libjsdll32.a库文件)
然后把库文件所在目录放到Link的连接库包含目录里,js32.dll放到windows系统目录或者是程序运行目录,再写一个测试程序,就能运行javascript脚本了.
想得蛮简单,可是SpiderMonkey那帮老兄在README里面的说明实在是太菜了,基本上按照他们的例子都是不能运行的,我再次祭出google大法,终于google上帝给我找到了一篇好文章:
    http://users.skynet.be/saw/SpiderMonkey.htm
按照这篇文章的例子,我的MinGW/GCC嵌入javascript终于顺利搞定了.例子代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <string>
#include <iostream>
/* include the JS engine API header */
#include "jsapi.h"

/* main function sets up global JS variables, including run time,
* a context, and a global object, then initializes the JS run time,
* and creates a context. */

int main(int argc, char **argv)
{
/*set up global JS variables, including global and custom objects */

JSRuntime *rt;
JSContext *cx;

/* initialize the JS run time, and return result in rt */
rt = JS_NewRuntime(8L * 1024L * 1024L);

/* if rt does not have a value, end the program here */
if (!rt)
  return 1;

/* create a context and associate it with the JS run time */
cx = JS_NewContext(rt, 8192);
/* if cx does not have a value, end the program here */
if (cx == NULL)
  return 1;

      /* 初始化内置JS对象和全局对象 */

      JSObject *global;
      JSClass global_class = {
    "global",0,
    JS_PropertyStub,JS_PropertyStub,JS_PropertyStub,JS_PropertyStub,
    JS_EnumerateStub,JS_ResolveStub,JS_ConvertStub,JS_FinalizeStub
  };
 
      global = JS_NewObject(cx, &global_class, NULL, NULL);
      JS_InitStandardClasses(cx, global);

    std::string script = "var today = Date(); today.toString();";
  jsval rval;
  uintN lineno = 0;
  JSBool ok = JS_EvaluateScript(cx, global, script.c_str(),
                      script.length(), "script", lineno, &rval);
     
      JSString *str = JS_ValueToString(cx, rval);
  std::cout << JS_GetStringBytes(str);
     
      JS_DestroyContext(cx);
      JS_DestroyRuntime(rt);
   
      return 0;
}
程序运行后,会调用Javascript脚本输出当前的日期和时间。

 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值