0

如何在 duktape c 函数中检查字符串对象/数字对象参数类型并解析来自字符串对象/数字对象的值。有像 duk_is_object() 这样的通用 api,但我需要正确的对象类型来解析值。

ex: 
ecmascript code
  var str1 = new String("duktape");
   var version = new Number(2.2);
 dukFunPrintArgs(str1,str2); 

duktape c function :
dukFunPrintArgs(ctx)
{
  // code to know whether the args is of type String Object / Number Object

}
4

1 回答 1

0

您在哪里找到如何在 duktape 中注册 C 函数的信息?那个地方当然也有关于如何访问传递给它的参数的详细信息。您已经在 duktape.org 的主页上找到了一个入门示例:

3 Add C function bindings

To call a C function from Ecmascript code, first declare your C functions:

/* Being an embeddable engine, Duktape doesn't provide I/O
 * bindings by default.  Here's a simple one argument print()
 * function.
 */
static duk_ret_t native_print(duk_context *ctx) {
  printf("%s\n", duk_to_string(ctx, 0));
  return 0;  /* no return value (= undefined) */
}

/* Adder: add argument values. */
static duk_ret_t native_adder(duk_context *ctx) {
  int i;
  int n = duk_get_top(ctx);  /* #args */
  double res = 0.0;

  for (i = 0; i < n; i++) {
    res += duk_to_number(ctx, i);
  }

  duk_push_number(ctx, res);
  return 1;  /* one return value */
}

Register your functions e.g. into the global object:

duk_push_c_function(ctx, native_print, 1 /*nargs*/);
duk_put_global_string(ctx, "print");
duk_push_c_function(ctx, native_adder, DUK_VARARGS);
duk_put_global_string(ctx, "adder");

You can then call your function from Ecmascript code:

duk_eval_string_noresult(ctx, "print('2+3=' + adder(2, 3));");

duktape 的核心概念之一是堆栈。值栈是存储参数的地方。在入门页面上阅读更多信息。

于 2017-11-15T07:54:41.400 回答