0

我试图实现一个原生 C duktape modSearch,但我被卡住了。我阅读了 DUKtape 文档并查看了https://github.com/svaarala/duktape/issues/194,但我仍然无法使其工作。

我创建了一个使用实现 modSearch 的简单测试,以下是详细信息:

  • 我有一个实现平方函数的简单 javascript。我称它为 testR.js:

    export.area = function(r){ return r*r; };

- 使用上述简单函数的文件称为 usetestR.js:

function main(){
// const square = require('./testR.js');   --> use this line for nodeJS
const square = require('testR.js');
var ts = square.area(8);

    // console.log(ts); -> used this line for nodeJS 
    print(ts);
}

main();

现在使用 duktape,我开始在 C 中实现函数 modSearch,如下所示:

/* Declaration */
void modSearch_register(duk_context *ctx) {
    duk_get_global_string(ctx, "Duktape");
    duk_push_c_function(ctx, mod_search, 4 /*nargs*/);
    duk_put_prop_string(ctx, -2, "modSearch");
    duk_pop(ctx);
}

mod_search

#include <stdio.h>
#include <string.h>
#include "duktape.h"

duk_ret_t mod_search(duk_context *ctx) {
/* Nargs was given as 4 and we get the following stack arguments:
 *   index 0: id
 *   index 1: require
 *   index 2: exports
 *   index 3: module
 */

 int     rc;

// Get ID
char *id        = duk_require_string(ctx, 0);

printf("ID => %s \n", id);
rc = strcmp(id, "testR.js");
if(rc == 0)
{
    printf("Module found, loading... \n");

    // Read File
    duk_push_object(ctx);
    duk_put_global_string(ctx, "exports");
    if(duk_peval_file(ctx,"testR.js" )!= 0)
        printf("Problem !!! \n");
    else{
        printf("Pass !!! \n");
        return 1;
    }
    return -1;
}

当我运行代码时,这就是我所拥有的:

ID => testR.js 
Module found, loading... 
Pass !!! 
TypeError: undefined not callable
    duk_js_call.c:776
    main usetestR.js:3
    global usetestR.js:8 preventsyield
error in executing file usetestR.js

你能帮我指出问题出在哪里吗?谢谢

4

1 回答 1

1

对不起,我想通了......也许这个例子可以在未来帮助其他人:)

以下是有效的 modSearch

duk_ret_t mod_search(duk_context *ctx) {
    /* Nargs was given as 4 and we get the following stack arguments:
     *   index 0: id
     *   index 1: require
     *   index 2: exports
     *   index 3: module
     */
char *src = NULL;
FILE *f   = NULL;
const char *filename = "/home/testR.js";

int  rc, len;

// Pull Arguments
char *id        = duk_require_string(ctx, 0);

printf("ID => %s \n", id);

rc = strcmp(id, "testR.js");
if(rc == 0)
{
    printf("Module found, loading... \n");
    // Read File and calculate its size (as DUKtape examples)
    f = fopen(filename, "rb");
    fseek(f, 0, SEEK_END);
    len = (int) ftell(f);

    // Rewind
    fseek(f, 0, SEEK_SET);

    src = malloc(len);
    fread(src, 1, len,f);
    fclose(f);
    duk_push_lstring(ctx, src, len);
    free(src);
    return 1;
  }

    // Error
    return -1;
}

运行程序,显示

ID => testR.js 
Module found, loading... 
64

了解了基础知识后,就有可能采用更复杂的方法来实现 modSearch。

于 2016-04-13T23:44:07.280 回答