当前位置: 首页 > 工具软件 > Duktape > 使用案例 >

引用Duktape

潘飞英
2023-12-01

​ 最近项目中需要使用JS引擎,在经历了V7引擎的正则表达式存在Bug、V8引擎实现多线程操作资源占用太大导致软件崩溃后,从网上找到Duktape引擎。Duktape 引擎对ECMAScript兼容性较好且项目比较活跃,授权协议为MIT。

引用Duktape

只需要将duktape.hduktape.cduk_config.h 添加到VS工程即可。

定义导出类

class CLog
{
public:
    CLog () {}
    void Info(const char* msg) {
        printf("[Info] %s\n", msg);
    }

    void Err(const char* msg) {
        printf("[Err] %s\n", msg);
    }

    void Warn(const char* msg) {
        printf("[Warn] %s\n", msg);
    }    
};

声明全局对象及操作函数

static CLog s_log;

static duk_ret_t Info(duk_context *ctx) {
    const char *msg = duk_safe_to_string(ctx, 0);

    duk_push_current_function(ctx);
    duk_get_prop_string(ctx, -1, "_ptr");
    CLog *log = static_cast<CLog*>(duk_to_pointer(ctx, -1));

    log->Info(msg);

    duk_push_boolean(ctx, 1);
    return 1;
}

static duk_ret_t Warn(duk_context *ctx) {
    const char *msg = duk_safe_to_string(ctx, 0);

    duk_push_current_function(ctx);
    duk_get_prop_string(ctx, -1, "_ptr");
    CLog *log = static_cast<CLog*>(duk_to_pointer(ctx, -1));

    log->Warn(msg);

    duk_push_boolean(ctx, 1);
    return 1;
}

static duk_ret_t Err(duk_context *ctx) {
    const char *msg = duk_safe_to_string(ctx, 0);

    duk_push_current_function(ctx);
    duk_get_prop_string(ctx, -1, "_ptr");
    CLog *log = static_cast<CLog*>(duk_to_pointer(ctx, -1));

    log->Err(msg);

    duk_push_boolean(ctx, 1);
    return 1;
}

static duk_ret_t GetMsg(duk_context *ctx) {
    duk_push_string(ctx, "测试 Test");
    return 1;
}

声明导出对象函数

void AddLogObj(duk_context *ctx) {
    struct {
        const char      *name;
        duk_c_function  fn;
    } fnItems[] = {
        {"Info"     , Info},
        {"Warn"     , Warn},
        {"Err"      , Err},
        {"GetMsg"   , GetMsg}
    };

    duk_push_global_object(ctx);
    duk_push_object(ctx);

    size_t fnCnt = sizeof(fnItems)/sizeof(fnItems[0]);
    for (size_t i = 0; i < fnCnt; ++i) {
        duk_push_c_function(ctx, fnItems[i].fn, 1);
        duk_push_pointer(ctx, &s_log);
        duk_put_prop_string(ctx, -2, "_ptr");
        duk_put_prop_string(ctx, -2, fnItems[i].name);
    }

    duk_put_prop_string(ctx, -2, "Log");
}

程序入口函数

int main(int argc, char *argv[]) {
    duk_context *ctx;

    if (argc < 2) { exit(1);}

    ctx = duk_create_heap_default();
    if (!ctx) { exit(1);}

    AddLogObj(ctx);

    duk_eval_string(ctx, "print(Log.Info(123)); print(Log.GetMsg());");


    duk_destroy_heap(ctx);    
    return 0;
}

代码下载

http://download.csdn.net/detail/sdhongjun/9609026

参考资料

https://github.com/civetweb/civetweb/blob/master/src/mod_duktape.inl

 类似资料: