c调用javascript

来源:互联网 发布:polyfit函数的算法 编辑:程序博客网 时间:2024/05/17 07:54
操作步骤:
1、下载获得js-1.60.tar.gz的tarball并解压,下载地址:http://ftp.mozilla.org/pub/mozilla.org/js/
2、 用vc6打开src目录下的js.mdp,vc6会提示你转换到新版的dsp,确定会得到3个dsp工程文件;
3、 分别设定这三个文件为Active Project同时分别编译得到js32.dll和js32.lib
4、 把上述2个文件以及src下的*.h复制到你的应用程序目录下(或者通过选项卡设定Project的头文件包含路径)
5 新建"Win32 console applation"型的工程,编写C代码进行测试,如下:
#include <string.h> //for strlen
#include <stdio.h>
#include "stdlib.h"
#include "string.h"
#define XP_WIN
#include "jsapi.h"
#pragma comment(lib, "js32.lib")

int main(int argc,const char* argv[])
{
JSRuntime *runtime = NULL;
/* pointer to our context */
JSContext *context = NULL;
/* pointer to our global JavaScript object */
JSObject *global = NULL;

    /* script to run (should return 100) */
const char *script = "var a=5;b=6;a+b;";
/* JavaScript value to store the result of the script */
jsval rval;

    /* create new runtime, new context, global object */
if ((!(runtime = JS_NewRuntime(1024L * 1024L)))
|| (!(context = JS_NewContext(runtime, 8192)))
|| (!(global = JS_NewObject(context, NULL, NULL, NULL)))
)
return EXIT_FAILURE;
/* set global object of context and initialize standard ECMAScript
*      objects (Math, Date, ...) within this global object scope */
if (!JS_InitStandardClasses(context, global))
return EXIT_FAILURE;

    /* now we are ready to run our script */
if (!JS_EvaluateScript(context, global, script, strlen(script), "script", 1, &rval))
return EXIT_FAILURE;

    printf("the script's result is \n%d\n",JSVAL_TO_INT(rval));

    /* clean up */
JS_DestroyContext(context);
JS_DestroyRuntime(runtime);
JS_ShutDown();
return EXIT_SUCCESS;
}
原创粉丝点击