C语言执行javascript代码

原理: 应用SpiderMonkey的js引擎可以执行javascript代码.

1.添加头文件

#include 
#include 
#include 
#include 

2.添加主函数

int main(int argc, char **argv)
{
    JSRuntime *RunTime = NULL;
    JSContext *ConText = NULL;
    JSObject *Global = NULL;
    jsval rval;
    const char *Script;

    if(argc != 2)
    {
        printf("入参个数错误\n");
        return 0;
    }

    Script = argv[1];

    printf("script is \"%s\"\n", Script);

    if(!(RunTime = JS_NewRuntime(1024L * 1024L)) || !(ConText = JS_NewContext(RunTime, 8192)) || !(Global = JS_NewObject(ConText, NULL, NULL, NULL)))
    {
        return EXIT_FAILURE;
    }

    if(!JS_InitStandardClasses(ConText, Global))
    {
        return EXIT_FAILURE;
    }

    if(!JS_EvaluateScript(ConText, Global, Script, strlen(Script), "script", 1, &rval))
    {
        return EXIT_FAILURE;
    }

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

    JS_DestroyContext(ConText);
    JS_DestroyRuntime(RunTime);
    JS_ShutDown();

    return EXIT_SUCCESS;
}

3.编译代码

gcc -o examle examle.c -L$HOME/local/normal/lib -ljs

4.运行程序

./examle "var a=1; var b=2; a+b"

5.执行结果

script is "var a=1; var b=2; a+b"
the script's result is 3

你可能感兴趣的:(C语言执行javascript代码)